Skip to Main Content
PHPUnit Pocket Guide
book

PHPUnit Pocket Guide

by Sebastian Bergmann
September 2005
Intermediate to advanced content levelIntermediate to advanced
90 pages
1h 53m
English
O'Reilly Media, Inc.
Content preview from PHPUnit Pocket Guide

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering PHP 7

Mastering PHP 7

Branko Ajzele

Publisher Resources

ISBN: 0596101031Errata Page