How can be any service injected into WebTestCase subclass in Symfony?

强颜欢笑 提交于 2021-01-28 08:26:04

问题


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

WebTestCase generates this constructor sample:

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

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

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


回答1:


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

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();

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



来源:https://stackoverflow.com/questions/50379327/how-can-be-any-service-injected-into-webtestcase-subclass-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!