Chapter 6. Fixtures
One of the most time consuming parts of writing tests is writing the code to set up the world in a known state and then return it to its original state when the test is complete. The known state is called the fixture of the test.
In Example 5, the fixture was simply an array stored in the
$fixture variable. Most of the time, though, the fixture will be more complex than a simple array, and the amount of code needed to set it up will grow accordingly. The actual content of the test gets lost in the noise of setting up the fixture. This problem gets even worse when you write several tests with similar fixtures. Without some help from the testing framework, we would have to duplicate the code that sets up the fixture for each test we write.
PHPUnit supports sharing the setup code. Before a test method is run, a template method called
setUp( ) is invoked.
setUp( ) is where you create the objects against which you will test. Once the test method has finished running, whether it succeeded or failed, another template method called
tearDown( ) is invoked.
tearDown( ) is where you clean up the objects against which you tested.
We can now refactor Example 5 and use
setUp( ) to eliminate the code duplication that we had before. First, we declare the instance variable,
$fixture, that we are going to use instead of a method-local variable. Then, we put the creation of the
Array fixture into the
setUp( ) method. Finally, we remove the redundant code from the test methods and ...