philipp
philipp

Reputation: 16495

Run command before all tests

I have created a Symfony Command to reset my Application to an initial state. To run that command from the cli I need to type:

php bin/console app:reset

I would like to run that command once before all unit tests. I could manage to do that before each test and surely before all classes. Therefore I used that code:

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

As mentioned above, that is working nice before each test and with setUpBeforeClass() I could have that before each class, but once before all tests would be sufficient, since that command take some time to run.

Upvotes: 13

Views: 11476

Answers (2)

Rich
Rich

Reputation: 15458

The Symfony docs explain how to do this: How to Customize the Bootstrap Process before Running Tests

In short, you need to modify the phpunit.xml.dist to call your own bootstrap instead of the default one (and delegate to the default bootstrap).

Upvotes: 8

Jakub Zalas
Jakub Zalas

Reputation: 36191

You could implement a test listener and use a static property to make sure your command is executed only once.

Example for 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;
        }
    }
}

You'll need to enable the test listener in your phpunit.xml config.

Read more:

Upvotes: 7

Related Questions