How do I write unit tests in PHP?

letgo picture letgo · Nov 11, 2008 · Viewed 69.2k times · Source

I've read everywhere about how great they are, but for some reason I can't seem to figure out how exactly I'm supposed to test something. Could someone perhaps post a piece of example code and how they would test it? If it's not too much trouble :)

Answer

Till picture Till · Nov 12, 2008

There is a 3rd "framework", which is by far easier to learn - even easier than SimpleTest, it's called phpt.

A primer can be found here: http://qa.php.net/write-test.php

Edit: Just saw your request for sample code.

Let's assume you have the following function in a file called lib.php:

<?php
function foo($bar)
{
  return $bar;
}
?>

Really simple and straight forward, the parameter you pass in, is returned. So let's look at a test for this function, we'll call the test file foo.phpt:

--TEST--
foo() function - A basic test to see if it works. :)
--FILE--
<?php
include 'lib.php'; // might need to adjust path if not in the same dir
$bar = 'Hello World';
var_dump(foo($bar));
?>
--EXPECT--
string(11) "Hello World"

In a nutshell, we provide the parameter $bar with value "Hello World" and we var_dump() the response of the function call to foo().

To run this test, use: pear run-test path/to/foo.phpt

This requires a working install of PEAR on your system, which is pretty common in most circumstances. If you need to install it, I recommend to install the latest version available. In case you need help to set it up, feel free to ask (but provide OS, etc.).