Unit Testing with PHPUnit

Now that you are familiar with object-oriented programming, it’s a good idea to get a taste of unit testing. This is a method of code testing that verifies whether individual units of source code are working correctly.

Unit testing provides the following benefits:

  • It allows for automation of the testing process.

  • It reduces the difficulty of discovering errors within more complex code.

  • Testing is often enhanced because attention is given to each unit.

Install PHPUnit with the PEAR installer. To do this, go to a Command or Terminal prompt, ensure that you have Administrator or Superuser privileges, and issue the two lines of code in Table E-3, according to your operating system. (On Windows systems, ignore and close any pop-up “Invalid configuration directive” alerts that may appear.)

Table E-3. Commands for Installing PHPUnit on different systems


Instructions to type from an Administrator Command prompt or a Terminal window


(4 instructions)

cd \Program Files\EasyPHP 3.0\php

pear channel-discover pear.phpunit.de

pear install phpunit/PHPUnit

Xcopy /E pear\*.* includes

Mac OS X

(3 instructions)

cd /Applications/MAMP/bin

pear channel-discover pear.phpunit.de

pear install phpunit/PHPUnit


(2 instructions)

pear channel-discover pear.phpunit.de

pear install phpunit/PHPUnit

The two main commands register the PEAR channel on your system, download PHPUnit, and install it. On Windows, you need the additional XCOPY command to resolve a file and path bug ...

Get Learning PHP, MySQL, and JavaScript 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.