Приглашаем посетить
Гумилев (gumilev.lit-info.ru)

Chapter 6.  Fixtures

Previous
Table of Contents
Next

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 use the newly introduced instance variable, $this->fixture, instead of the method-local variable $fixture with the assertEquals( ) assertion method.

	<?php 
	require_once 'PHPUnit2/Framework/TestCase.php';

	class ArrayTest extends PHPUnit2_Framework_TestCase { 
    protected $fixture;

    protected function setUp( ) {
      // Create the Array fixture.
      $this->fixture = Array( );
    }
		public function testNewArrayIsEmpty( ) {
      // Assert that the size of the Array fixture is 0.
			$this->assertEquals(0, sizeof($this->fixture)); 
    }

    public function testArrayContainsAnElement( ) { 
      // Add an element to the Array fixture.    
      $this->fixture[] = 'Element';

			// Assert that the size of the Array fixture is 1.
			$this->assertEquals(1, sizeof($this->fixture));
    }
  }
  ?>

setUp( ) and tearDown( ) will be called once for each test method run. Although it might seem frugal to run the set up and tear down code only once for all the test methods in a test-case class, doing so would make it hard to write tests that are completely independent of each other.

Not only are setUp( ) and tearDown( ) run once for each test method, but the test methods are run in fresh instances of the test-case class (see "PHPUnit's Implementation," later in this book).


Previous
Table of Contents
Next