Symfony 4: how to load DataFixtures in a KernelTestCase

℡╲_俬逩灬. 提交于 2019-12-12 00:48:00

问题


I got DataFixtures set up, that I can load via console into my test database.

$ php bin/console doctrine:fixtures:load --env=test -n
> purging database
> loading App\DataFixtures\PropertyFixtures
> loading App\DataFixtures\UserFixtures
> loading App\DataFixtures\UserPropertyFixtures

works like a chram

But I am lost how to load these fixtures automatically with my service unit tests, without having to run the command manually before testing. There has to be another way!

What I found so far is descriptions for testing with older versions of symfony or for testing Controllers. Who wants to test Controllers anyway, if you can avoid it?

The Liip\FunctionalTestBundle also seems to work only for WebTestCases at least I have seen no way to extend or replace the usual KernelTestCase.

So is there any way I can maybe run the command with the setUp() method of my test class?

Any link to a tutorial for symfony 4? Any example for a service? I cannot imagine, that I am the only person with that problem.


回答1:


I got a solution and although it is not full of beauty and style here it is. More elegant alternatives are appreciated.

I extended my Kernel class found in Kernel.php with a class called AppKernel. To activate it for tests and only those I changed my phpunit.xml file:

<php>
    <ini name="error_reporting" value="-1" />
    <env name="KERNEL_CLASS" value="App\AppKernel" />

So now only for tests this class is loaded.

In the AppKernel Class I extended the boot method as follows:

public function boot()
{
    parent::boot();
    $this->importDataFixtures();
}

/**
 * Loads the tests data for DataFixtures when we start phpUnit.
 */
protected function importDataFixtures()
{
    system('php /var/www/octopus/bin/console doctrine:fixtures:load --env=test -n');
}

So of course the call of the import via system is ugly, but it works. If somebody has a better idea, please let my know.



来源:https://stackoverflow.com/questions/51159781/symfony-4-how-to-load-datafixtures-in-a-kerneltestcase

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