本文介绍了Symfony 4:如何在KernelTestCase中加载DataFixtures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了DataFixtures,可以通过控制台将其加载到测试数据库中。

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

工作方式类似于chram

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!

到目前为止,我发现的是使用较旧版本的symfony进行测试或对Controller进行测试的描述。

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?

Liip\FunctionalTestBundle似乎也只适用于WebTestCases,至少我没有办法扩展或替换通常的KernelTestCase。

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

那么我有什么方法可以通过测试类的setUp()方法运行命令?

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

是否有指向symfony 4教程的链接?有服务示例吗?我无法想象,我是唯一遇到此问题的人。

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.

推荐答案

我有一个解决方案,尽管它并不完整这里是美丽和风格。我们会欣赏更优雅的替代方法。

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

我用一个名为AppKernel的类扩展了在Kernel.php中找到的Kernel类。
要激活它以进行测试,并且只有我更改了phpunit.xml文件,才能进行激活:

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.

在AppKernel类中,我将启动方法扩展如下:

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.

这篇关于Symfony 4:如何在KernelTestCase中加载DataFixtures的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:21