Search code examples
unit-testingdoctrinesymfony4

Symfony 4: how to load DataFixtures in a KernelTestCase


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.


Solution

  • 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.