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
Class
go into a classClassTest
.ClassTest
inherits (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 ...
Get PHPUnit Pocket Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.