Reputation: 9758
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?
Upvotes: 11
Views: 6518
Reputation: 36562
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 ...
}
Upvotes: 8
Reputation: 2964
You can override the function
protected function onNotSuccessfulTest(Exception $e)
with for instance;
$this->tearDownAfterClass();
throw $e;
Upvotes: 2