Using PHPUnit, how to run initialization code before running any tests?

We are currently running code to configure the database in setUpBeforeClass. However, this is done before testing each test class. Is it possible for the code to run once before running any tests, and possibly run some code when all the tests are complete too?

+8
phpunit
source share
3 answers

This is exactly what is meant to handle the bootstrap file. By default, PHPUnit will execute the code in bootstrap.php in the current directory. You can use the phpunit.xml or --bootstrap configuration file to point to another file.

This file is executed exactly once before trying to find the tests that will run. It allows you to configure the inclusion path, autoloader, constants, etc., before creating or running any tests.

+12
source share

I agree with Kris's comment that you want to avoid this behavior, but if you need to, maybe 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.

0
source share

Why do you need this? Unit tests must be independent of each other, and therefore all preconditions must also be restored to the same state before each test runs.

If you feel the need to have an initialization method that runs once for the whole package, your tests are probably not configured correctly.

-2
source share

All Articles