如何将任何服务注入 Symfony 中的 WebTestCase 子类? [英] How can be any service injected into WebTestCase subclass in Symfony?

查看:53
本文介绍了如何将任何服务注入 Symfony 中的 WebTestCase 子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我遗漏了什么……嗯,我想是的,但找不到答案.

Maybe I am missing something... doh, I think so, but could not find an answer to that.

WebTestCase 生成此构造函数示例:

WebTestCase generates this constructor sample:

public function __construct(?string $name = null, array $data = [], string $dataName = '')
{
     parent::__construct($name, $data, $dataName);
}

试图将我的服务添加为第一个或最后一个参数 - Symfony 抛出错误:

Was trying to add my service as the first or last argument - Symfony throws an error:

Type error: Too few arguments to function Tests\AppBundle\Manager\ContactManagerTest::__construct(), 0 passed in /Library/WebServer/Documents/HEPT/vendor/bin/.phpunit/phpunit-5.7/src/Framework/TestSuite.php on line 568 and at least 1 expected in /Library/WebServer/Documents/HEPT/tests/AppBundle/Manager/ContactManagerTest.php:22

我应该以某种方式直接使用容器吗?如果有桥接类,为什么自动装配对 WebTestCase 类不起作用?

Should I somehow use container directly? Why is autowiring not working for WebTestCase classes if there is a bridge class?

推荐答案

WebTestCase 用于 PHPUnit 的上下文中(与 Symfony 及其依赖注入无关).

WebTestCase are used in the context of PHPUnit (which has nothing to do with Symfony and its dependency injection).

它们实际上生成了内核及其容器,请参阅从 Symfony 源代码:

They actually generate the kernel and its container, see this piece of code extracted from Symfony source code:

protected static function createClient(array $options = array(), array $server = array())
{
    $kernel = static::bootKernel($options);
    $client = $kernel->getContainer()->get('test.client');
    $client->setServerParameters($server);
    return $client;
}

这意味着您可以像这样轻松访问容器:

This means that you can easily access the container like this:

$kernel = static::bootKernel($options);
$container = $kernel->getContainer();

另请注意,static::$kernel->getContainer() 在您创建客户端以进行测试后立即可用.

Please note also that static::$kernel->getContainer() is available as soon as you created your client to make your test.

这篇关于如何将任何服务注入 Symfony 中的 WebTestCase 子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆