运行 所有测试前的命令

Run command before all tests

我创建了一个 Symfony 命令来将我的应用程序重置为初始状态。对于来自 cli 的 运行 该命令,我需要键入:

php bin/console app:reset

我想 运行 该命令 在所有 单元测试之前执行一次。我可以设法做到这一点 在每个测试之前 并且肯定在 所有 classes 之前。因此我使用了那个代码:

public function setUp()
{
    $kernel = new \AppKernel('test', true);
    $kernel->boot();
    $app = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
    $app->setAutoExit(false);

    $app->run(new ArrayInput([
        'command' => 'app:reset', ['-q']
    ]), new NullOutput());
}

如上所述,在每次测试之前效果很好,使用 setUpBeforeClass() 我可以在每次 class 之前使用它,但是在所有测试之前一次就足够了,因为该命令需要一些时间至 运行.

您可以实施 a test listener 并使用静态 属性 来确保您的命令只执行一次。

PHPUnit 5.4 示例:

<?php

use PHPUnit\Framework\TestCase;

class AppResetTestListener extends PHPUnit_Framework_BaseTestListener
{
    static $wasCalled = false;

    public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
    {
        if (!self::$wasCalled) {
            // @todo call your command

            self::$wasCalled = true;
        }
    }
}

您需要在 phpunit.xml 配置中 enable the test listener

阅读更多:

Symfony 文档解释了如何做到这一点:How to Customize the Bootstrap Process before Running Tests

简而言之,您需要修改 phpunit.xml.dist 以调用您自己的 bootstrap 而不是默认的(并委托给默认的 bootstrap)。