Prev Next

Chapter 4. Writing Tests for PHPUnit

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

Example 4.1: Testing Array and sizeof() with PHPUnit

<?php
require_once 'PHPUnit/Framework.php';

class ArrayTest extends PHPUnit_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));
}
}
?>

 

Whenever you are tempted to type something into a print statement or a debugger expression, write it as a test instead.

 
  --Martin Fowler

Example 4.1 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 PHPUnit_Framework_TestCase.

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

    Alternatively, you can use the @test annotation in a method's docblock to mark it as a test method.

  4. Inside the test methods, assertion methods such as assertEquals() (see Table 20.1) are used to assert that an actual value matches an expected value.

Prev Next