首页 > 解决方案 > Symfony 4:如何在 KernelTestCase 中加载 DataFixtures

问题描述

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

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

像个骗子一样工作

但是我不知道如何使用我的服务单元测试自动加载这些装置,而无需在测试之前手动运行命令。必须有另一种方式!

到目前为止,我发现的是使用旧版本的 symfony 进行测试或测试控制器的描述。如果可以避免的话,谁还想测试控制器?

Liip\FunctionalTestBundle 似乎也仅适用于 WebTestCases,至少我没有看到任何扩展或替换通常的 KernelTestCase 的方法。

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

任何指向 symfony 4 教程的链接?任何服务示例?我无法想象,我是唯一有这个问题的人。

标签: unit-testingdoctrinesymfony4

解决方案


我得到了一个解决方案,虽然它在这里并不充满美感和风格。更优雅的替代品受到赞赏。

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

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

所以现在只为测试加载这个类。

在 AppKernel 类中,我扩展了引导方法,如下所示:

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');
}

因此,通过系统导入的调用当然是丑陋的,但它确实有效。如果有人有更好的主意,请告诉我。


推荐阅读