Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 515
philipp Avatar asked Jun 06 '16 08:06

philipp


2 Answers

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

like image 86
Rich Avatar answered Nov 09 '22 20:11

Rich


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:

  • Extending PHPUnit
  • Test listeners
like image 7
Jakub Zalas Avatar answered Nov 09 '22 18:11

Jakub Zalas