我正在尝试创建一个基本上是Stripe包装器的服务。在构造方法中,我想通过服务的构造方法传递api secret和publishable键,该方法在.env文件中设置为环境变量。但是每次我在这个包装器上运行phpunit测试时,我都会收到这个错误:
Missing argument 1 for AppBundle\Util\StripeService::__construct(), called in /Users/name/Sites/app/tests/AppBundle/Util/StripeServiceTest.php
这是我的设置:
# .env
SYMFONY__STRIPE_SECRET=''
SYMFONY__STRIPE_PUBLISHABLE=''
# config_test.yml
parameters:
stripe.secret: '%env(stripe_secret)%'
stripe.publishable: '%env(stripe_publishable)%'
services:
app.stripe_service:
class: AppBundle\Util\StripeService
arguments: ['%stripe.secret%', '%stripe.publishable%']
# StripeService.php
namespace AppBundle\Util;
class StripeService {
public function __construct($secretKey, $publishableKey)
{
$this->secretKey = $secretKey;
$this->$publishableKey = $publishableKey;
}
# StripeServiceTest.php
namespace Tests\AppBundle\Util;
use AppBundle\Util\StripeService;
use PHPUnit\Framework\TestCase;
class StripeServiceTest extends TestCase {
protected function setUp()
{
require_once realpath(__DIR__ . '/../../../app/AppKernel.php');
$kernel = new \AppKernel('test', true);
$kernel->boot();
}
public function testFindEvent()
{
$stripe = new StripeService();
$stripe->findEvent('test');
}
}
# AppKernel.php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
# This is where I am loading in the variables from .env
try {
(new Dotenv\Dotenv(realpath(__DIR__ . '/..')))->load();
$envParameters = $this->getEnvParameters();
$loader->load(function($container) use($envParameters) {
$container->getParameterBag()->add($envParameters);
});
} catch (Dotenv\Exception\InvalidPathException $e) {
}
}
}
我按照docs中有关服务容器的说明进行了操作,并按照[此博客文章]使用vlucas / phpdotenv从.env文件中获取变量。我错过了什么,或者当我的测试初始化new StripeService()
它无法获取config_test.yml
中列出的参数时,我错误地设置了一些内容?
答案 0 :(得分:1)
StripeServiceTest应如下所示:
class StripeServiceTest extends TestCase {
protected $container;
protected function setUp()
{
require_once realpath(__DIR__ . '/../../../app/AppKernel.php');
$kernel = new \AppKernel('test', true);
$kernel->boot();
$this->container = $kernel->getContainer();
}
public function testFindEvent()
{
$stripe = $this->container->get('app.stripe_service');
$stripe->findEvent('test');
}
}
答案 1 :(得分:1)
您尝试实例化类(new StripeService()
)而未传递StripeService::__constuctor()
如果您想使用在config_test.yml
中定义的服务实例,则需要使用“容器”
...
$stripeService = $kernel->getContainer()->get('app.stripe_service');
这将为您提供已定义参数的实例。