O'Reilly logo

PHPUnit Pocket Guide by Sebastian Bergmann

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. PHPUnit’s Goals

So far, we only have two tests for the Array built-in and the sizeof( ) function. When we start to test the numerous array_*( ) functions PHP offers, we will need to write a test for each of them. We could write all these tests from scratch. However, it is much better to write a testing infrastructure once and then write only the unique parts of each test. PHPUnit is such an infrastructure.

Example 5 shows how we have to rewrite our two tests from Example 4 so that we can use them with PHPUnit.

Example 5. Testing Array and sizeof( ) with PHPUnit
<?php
require_once 'PHPUnit2/Framework/TestCase.php';

class ArrayTest extends PHPUnit2_Framework_TestCase {
  public function testNewArrayIsEmpty( ) {
    // Create the Array fixture.
    $fixture = Array( );

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

    // Add an element to the Array fixture.    
		$fixture[] = 'Element';
 
		// Assert that the size of the Array fixture is 1. 
		$this->assertEquals(1, sizeof($fixture));
  }
}
?>

Example 5 shows the basic steps for writing tests with PHPUnit:

  1. The tests for a class Class go into a class ClassTest.

  2. ClassTest inherits (most of the time) from PHPUnit2_ Framework_TestCase.

  3. The tests are public methods that expect no parameters and are named test*.

  4. Inside the test methods, assertion methods such as assertEquals( ) (see Table 6) are used to assert that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required