Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in PHPUnit how to force tearDownAfterClass() to run in case of unexpected exceptions

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?

like image 479
Reza S Avatar asked Sep 03 '12 03:09

Reza S


People also ask

How do I assert exceptions in PHPUnit?

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.

What are fixtures in PHP?

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.


1 Answers

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 ...
}
like image 148
David Harkness Avatar answered Sep 22 '22 21:09

David Harkness