PHPUnit setup before running first test and tear down after running last test

My two spontaneous ideas that don't use "Test Suites". One that does is at the bottom.

Test Listener

Using PHPUnits test listeners you could do a

  public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
  {
       if($suite->getName() == "yourDBTests") { // set up db
  }

  public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
  {
       if($suite->getName() == "yourDBTests") { // tear down db
  }

You can define all your DB tests in a testsuite in the xml configuration file like shown in the docs

<phpunit>
  <testsuites>
    <testsuite name="db">
      <dir>/tests/db/</dir>
    </testsuite>
    <testsuite name="unit">
      <dir>/tests/unit/</dir>
    </testsuite>
  </testsuites>
</phpunit>

Bootstrap

Using phpunits bootstrap file you could create a class that creates the DB and tears it down in it's own __destruct method when the process ends.

Putting the reference to the object in some global scope would ensure the object only gets destructured at the end off all tests. ( As @beanland pointed out: Using register_shutdown_function() makes a whole lot more sense!)


Using Test suites:

http://www.phpunit.de/manual/3.2/en/organizing-test-suites.html shows:

<?php

class MySuite extends PHPUnit_Framework_TestSuite
{
    public static function suite()
    {
        return new MySuite('MyTest');
    }

    protected function setUp()
    {
        print "\nMySuite::setUp()";
    }

    protected function tearDown()
    {
        print "\nMySuite::tearDown()";
    }
}

class MyTest extends PHPUnit_Framework_TestCase
{
    public function testWorks() {
        $this->assertTrue(true);
    }
}

this works well in PHPUnit 3.6 and will work in 3.7. It's not in the current docs as the "Test suite classes" are somewhat deprecated/discouraged but they are going to be around for quite some time.


Note that tearing down and setting up the whole db for each test case can be quite useful to fight inter-test-dependencies but if you don't run the tests in memory (like sqlite memory) the speed might not be worth it.


I recently encountered something where I needed to solve the very same issue. I tried Edorian's answer with the __destruct method of a custom class, but it seemed to be run at the end of every test rather than at the conclusion of all tests.

Instead of using a special class in my bootstrap.php file, I utilized PHP's register_shutdown_function function to handle database cleanup after the conclusion of all my tests, and it seemed to work perfectly.

Here's an example of what I had in my bootstrap.php file

register_shutdown_function(function(){
   some_db_cleanup_methods();
});

Tags:

Php

Phpunit