Php – How to write unit tests in PHP?


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 🙂

Best Solution

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:

Edit: Just saw your request for sample code.

Let's assume you have the following function in a file called lib.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:

foo() function - A basic test to see if it works. :)
include 'lib.php'; // might need to adjust path if not in the same dir
$bar = 'Hello World';
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.).