How do I write unit tests in PHP? [closed] How do I write unit tests in PHP? [closed] php php

How do I write unit tests in PHP? [closed]


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:

<?phpfunction 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--<?phpinclude '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.).


There are two frameworks you can use for unit testing. Simpletest and PHPUnit, which I prefer. Read the tutorials on how to write and run tests on the homepage of PHPUnit. It is quite easy and well described.


You can make unit testing more effective by changing your coding style to accommodate it.

I recommend browsing the Google Testing Blog, in particular the post on Writing Testable Code.