February 11th, 2010


11
Feb 10

Getting Started With PHPUnit

We all agree that testing code is better than not testing it right? So why do we tend to avoid writing unit tests to make sure that we are writing code that works? I’m looking at you PHP guys. Good thing there is PHPUnit and it is as easy as can be to get started with it.

First you have to discover the channel:

pear channel-discover pear.phpunit.de
pear channel-discover pear.symfony-project.com

Sidenote: phpunit.de has many useful packages in it including phpcpd, phpdcd, and phploc.

Then you install it (I usually install all of the dependencies with PHPUnit, but you don’t really have to).

pear install phpunit/PHPUnit

After that you can start writing tests.

Say you have a simple class like this:

<?php
class needsTesting{
	public function divide($a, $b){
		return $a/$b;
	}
}

Your unit test file would be this (prior to adding any test cases to it):

<?php 
 
require_once 'PHPUnit/Framework.php';
 
require_once 'needsTesting.php';
 
class needsTestingTest extends PHPUnit_Framework_TestCase {
	/**
	 * @var needsTesting
	 */
	protected $object;
 
	/**
	 * This method is called before a test is executed.
	 */
	protected function setUp() {
		$this->object = new needsTesting;
	}
 
	/**
	 * This method is called after a test is executed.
	 */
	protected function tearDown() {
	}
 
	public function testDivide() {
 
	}
}

After you have added the obvious test cases, your testDivide() function should look something like this:

<?php
//[...]
	public function testDivide() {
		$array_a = array(
			10,
			20,
			30,
			40,
			50,
		);
		$array_b = array(
			2,
			4,
			6,
			8,
			0,
		);
		$array_expected = array(
			5,
			5,
			5,
			5,
			0,
		);
		foreach($array_a as $k=>$a){
			$b = $array_b[$k];
			$expected = $array_expected[$k];
			$result = $this->object->divide($a, $b);
 
			$this->assertEquals($expected, $result);
		}
	}
//[...]

Running the code is quite easy, if your ide has a PHPUnit extension (like Netbeans does) you can run it from there, or you can run it from the command line (in the folder you are writing the tests in):

 
phpunit needsTesting

Since one of the tests will give you an error, you should get this:

 
 
PHPUnit 3.4.9 by Sebastian Bergmann.
 
E
 
Time: 0 seconds, Memory: 5.25Mb
 
There was 1 error:
 
1) needsTesting::testDivide
Division by zero
 
[...]/needsTesting.php:4
[...]/needsTestingTest.php:56
 
FAILURES!
Tests: 1, Assertions: 4, Errors: 1.

Now it is up to you to decide how your application handles the Divide by 0 error that you got (or any other errors for that matter). While testing first is a good way to define exactly how your app should work, testing after is good too (as long as you are testing it is a good thing).

Check it out:

http://www.phpunit.de/manual/current/en/