Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run PHPUnit Tests in Certain Order

Is there a way to get the tests inside of a TestCase to run in a certain order? For example, I want to separate the life cycle of an object from creation to use to destruction but I need to make sure that the object is set up first before I run the other tests.

like image 293
dragonmantank Avatar asked Aug 13 '08 19:08

dragonmantank


People also ask

What is the PHPUnit XML configuration file used to organize tests?

The <testsuite> Element.

How do I run PHPUnit?

How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.

Is PHPUnit a framework?

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks. The currently supported versions are PHPUnit 9 and PHPUnit 8.


2 Answers

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.

like image 159
mjs Avatar answered Sep 29 '22 13:09

mjs


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?

like image 20
Fabio Gomes Avatar answered Sep 29 '22 11:09

Fabio Gomes