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?
Use expectExceptionMessage if the message is important, or if it is the only way to see where something went wrong. Use try catch if you need to validate specific properties of the exception. For this post, PHPUnit 9.5 and PHP 8.0 were used. If you want to run the tests for yourself, you can find them on github.
Doctrine fixtures is a PHP library that loads a set of data fixtures fully written in PHP. Creating a fixtures file is simple, you only have to create a PHP class that implements the FixtureInterface and instantiate as many object as you want to store.
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 ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With