Currently we run code to setup the database in setUpBeforeClass. However this runs before every test class is tested. Is it possible to have code run once before any tests are run, and maybe run some code when all tests are complete too?
3 Answers
This is precisely what the bootstrap file is designed to handle. By default PHPUnit will execute the code in bootstrap.php in the current directory. You can use the phpunit.xml configuration file or the --bootstrap command-line switch to point to a different file.
This file is executed exactly once before trying to locate the tests to be run. It allows you to set up an include path, autoloader, constants, etc. before instantiating or running any tests.
I agree with Kris's comment that you want to avoid this sort of behavior, but if you need to, perhaps you could do something like this:
class My_PHPUnit_Framework_TestCase extends PHPUnit_Framework_TestCase {
function __construct() {
parent::__construct();
// Insert your one time setup scripts here
}
}
Then make sure your tests extend My_PHPUnit_Framework_TestCase instead of PHPUnit_Framework_TestCase.
Why would you want to do that? Unit tests should be independent of each other, and thus should all preconditions also be restored to the same state before every test is run.
If you feel the need to have an initialization method that runs once for the entire suite, your tests are probably not set up right.