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:
The tests for a class
Classgo into a classClassTest.ClassTestinherits (most of the time) fromPHPUnit2_ Framework_TestCase.The tests are public methods that expect no parameters and are named
test*.Inside the test methods, assertion methods such as
assertEquals( )(see Table 6) are used to assert that ...