11

So every time I encounter unexpected exceptions in PHPUnit (such as fails to insert into db because of an integrity check) my tests fail and it errors out without running tearDownAfterClass() function. This will leave my database in a messy state so I have to manually go and clean it up. Is there a way to ensure tearDownAfterClass() is always executed?

0

2 Answers 2

8

PHPUnit will call tearDownAfterClass even when there are errors and failures in test methods. It will not call it when setUpBeforeClass throws an exception. In order to ensure that your database is cleaned up, move the cleanup code into a new method that you call from tearDownAfterClass and the catch clause in setUpBeforeClass.

function FooTest extends PHPUnit_Framework_TestCase
{
    static function setUpBeforeClass() {
        try {
            ... setup code that might fail ...
        }
        catch (Exception $e) {
            self::cleanupDatabase();
            throw $e;  // so the tests will be skipped
        }
    }

    static function tearDownAfterClass() {
        self::cleanupDatabase();
    }

    static function cleanupDatabase() {
        ... clean ...
    }

    ... test methods ...
}
0
2

You can override the function

protected function onNotSuccessfulTest(Exception $e) 

with for instance;

$this->tearDownAfterClass();
throw $e;
2
  • 3
    Warning: This will call tearDownAfterClass for every test method that fails or errors--not once at the end for the entire class. Commented Sep 3, 2012 at 19:59
  • 1
    -1 It also doesn't solve the problem because onNotSuccessfulTest isn't called when setUpBeforeClass throws an exception. Commented Sep 3, 2012 at 20:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.