Setting up the fixture in PHPUnit

When running our tests we should begin with a know stage, called the fixture, and for that we might need to initialize variables etc. And after we finish the tests we might have some cleaning up to do.

If you need to have custom code run before you execute them. PHPUnit allows you to configure a specific file to be run before the test execution.

This directive in your phpunit.xml configuration file will execute the bootstrap.php fiel before the tests: :

<phpunit bootstrap="tests/bootstrap.php" >
    <!-- ... -->

The bootstrap file can also be specified in the command line argument:

phpunit --bootstrap bootstrap.php

If every method is the class needs the same setup we might use provided functions to save ourselves from repeating the code.

PHPUnit has setUp() and tearDown methods that run before and after every method. We might use these for example to initialize variables.

Additionally, setUpBeforeClass() and tearDownAfterClass methods are being run before any method in the class has been executed and after all of them finish, respectively. These might be useful to setting up for example a database connection. However, one has to keep in mind that that when tests share a fixture and are not fully independent it makes them harder to debug.