PHPUnit is such an infrastructure. It is a family of PEAR packages (PHPUnit, PHPUnit2) that is available from the PHP Extension and Application Repository (PEAR), a framework and distribution system for reusable PHP components. You can install it using the PEAR Installer by running.
| pear install --alldeps phpunit2 |
Due to PEAR's version naming standard, the PHPUnit package for PHP 5 is PHPUnit2.
The following example shows how you have to write your two tests to use them with PHPUnit.
Example(Testing array and sizeof() with phpunit2):
| 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 shows the basic steps for writing tests with PHPUnit:
| $ phpunit ArrayTest PHPUnit 2.3.6 by Sebastian Bergmann. .................... Time: xxxxxxxx OK(2 tests) |
For each test run, the PHPUnit command-line tool prints one character to indicate progress:
PHPUnit distinguishes between failures and errors. A failure is a violated PHPUnit assertion.
An error is an unexpected exception or a PHP error. Sometimes this distinction proves useful,
since errors tend to be easier to fix than failures. If you have a big list of problems, it is best
to tackle the errors first and see if you have any failures left when you have fixed them all.
| $ phpunit ArrayTest PHPUnit 2.3.0 by Sebastian Bergmann. .F Time: 0.001147 There was 1 failure: 1) testArrayContainsAnElement(ArrayTest) expected same: <0> was not: <1> /home/sb/ArrayTest.php:21 FAILURES!!! Tests run: 2, Failures: 1, Errors: 0, Incomplete Tests: 0. |
The report shows where the failure occurs in the test code: in the test method
testArrayContainsAnElement() of the test case class ArrayTest, in line 21 of
the /home/sb/ArrayTest.php test code source file.