Run PHPUnit Tests in Certain Order Run PHPUnit Tests in Certain Order php php

Run PHPUnit Tests in Certain Order


PHPUnit supports test dependencies via the @depends annotation.

Here is an example from the documentation where tests will be run in an order that satisfies dependencies, with each dependent test passing an argument to the next:

class StackTest extends PHPUnit_Framework_TestCase{    public function testEmpty()    {        $stack = array();        $this->assertEmpty($stack);        return $stack;    }    /**     * @depends testEmpty     */    public function testPush(array $stack)    {        array_push($stack, 'foo');        $this->assertEquals('foo', $stack[count($stack)-1]);        $this->assertNotEmpty($stack);        return $stack;    }    /**     * @depends testPush     */    public function testPop(array $stack)    {        $this->assertEquals('foo', array_pop($stack));        $this->assertEmpty($stack);    }}

However, it's important to note that tests with unresolved dependencies will not be executed (desirable, as this brings attention quickly to the failing test). So, it's important to pay close attention when using dependencies.


Maybe there is a design problem in your tests.

Usually each test must not depend on any other tests, so they can run in any order.

Each test needs to instantiate and destroy everything it needs to run, that would be the perfect approach, you should never share objects and states between tests.

Can you be more specific about why you need the same object for N tests?


The correct answer for this is a proper configuration file for tests. I had the same problem and fixed it by creating testsuite with necessary test files order:

phpunit.xml:<phpunit        colors="true"        bootstrap="./tests/bootstrap.php"        convertErrorsToExceptions="true"        convertNoticesToExceptions="true"        convertWarningsToExceptions="true"        strict="true"        stopOnError="false"        stopOnFailure="false"        stopOnIncomplete="false"        stopOnSkipped="false"        stopOnRisky="false">    <testsuites>        <testsuite name="Your tests">            <file>file1</file> //this will be run before file2            <file>file2</file> //this depends on file1        </testsuite>    </testsuites></phpunit>