PHPUnit is the canonical unit testing framework for PHP. Even for simple projects and learning exercises, unit testing pays big dividends. This article provides a way to install and configure PHPUnit on Linux. This article assumes you’ve installed Composer, the popular PHP dependency manager. I used the following two lines to install Composer:

Step 1. Add src and tests directories to your project’s root. These aren’t absolute directory names required, but you’ll see these directory names referenced in following steps. If you change these names be sure to change the corresponding names in subsequent steps.

Step 2. Add the following Composer file, named composer.json in your project’s root.

Set the name, description, and license keys with your project’s info. The autoload key uses the psr-0 standard to autoload PHP class files located in the specified directory.

Then run composer from your project’s root to install PHPUnit and its dependencies. To ensure PHPUnit installed correctly, run this command from the command line:

(Note: If you’d rather not use Composer to install PHPUnit, there are alternative installation instructions on the PHPUnit site.)

If the PHPUnit version is correctly reported you’re ready for Step 3.

Step 3. Add a phpunit.xml file to your project’s root. This XML file provides configuration info to PHPUnit. There are many other configuration settings than what’s shown below available–this step keeps the configuration simple. Check PHPUnit’s documentation for the other configuration options available.

The bootstrap key identifies the autload file that causes your classes (the ones that you are testing) to be loaded. The colors key tells PHPUnit to show command line test results in color (ie, green for pass, red for fail).

The testsuites key identifies groups of tests (“test suites”) and the directory where the PHP tests files are located. When you run phpunit on the command line without any arguments all of the test suites identified here are performed. You can use PHPUnit’s --testsuite flag to run a single test suite. For example, if you had a test suite named Controller tests the following command line would run that test suite only:

The name you provide for test suites is case-sensitive. When a test suite is performed, the tests in its top-level directory, as well as any in any child directory are performed.

Learning how to use PHPUnit is central to learning PHP well, and, as you can see, getting it up and running is easy.

Leave a Reply

Your email address will not be published. Required fields are marked *