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.

Leave a Comment