Programming
Article
By Paul Annesley

pTest: PHP Unit Tester in 9 Lines Of Code

By Paul Annesley

I was recently working on a command line PHP tool, and didn’t have easy access to our normal PHP unit testing framework built around SimpleTest. After a few lines of non-test-driven-development, I started to freak out a bit – I guess I’ve fallen for the view that if code doesn’t have tests, it’s broken.

I didn’t need support for mock objects or complicated assertions – just a bare basic assertTrue() would do the trick. So, I present “pTest”, in 9 lines of code:


/**
 * pTest - PHP Unit Tester
 * @param mixed $test Condition to test, evaluated as boolean
 * @param string $message Descriptive message to output upon test
 */
function assertTrue($test, $message)
{
	static $count;
	if (!isset($count)) $count = array('pass'=>0, 'fail'=>0, 'total'=>0);

	$mode = $test ? 'pass' : 'fail';
	printf("%s: %s (%d of %d tests run so far have %sed)n",
		strtoupper($mode), $message, ++$count[$mode], ++$count['total'], $mode);
}

Here’s a few contrived test cases to demonstrate:


assertTrue(1 + 1 == 2, 'one plus one should equal two');
assertTrue(false, 'false should be true (this one will fail)');
assertTrue(!false, 'false should be false');

And the sample output:


PASS: one plus one should equal two (1 of 1 tests run so far have passed)
FAIL: false should be true (this one will fail) (1 of 2 tests run so far have failed)
PASS: false should be false (2 of 3 tests run so far have passed)

If you’re viewing the output in a web browser, you could easily wrap each output message in a <p> tag. Or if you’re using a non-broken browser you could serve the response with header('Content-Type: text/plain');.

Obviously this isn’t to be taken too seriously. Then again, I found it extremely useful to drop into the few command line scripts I was working on.

Another use I can see for such a simple testing function is introducing the uninitiated into the world of unit testing. I know that before I got into it, the biggest barrier was the complexity of the frameworks. Perhaps pTest will give beginners a starting point, from which they can move onto more feature-rich frameworks like PHPUnit or SimpleTest once they outgrow the humble assertTrue().

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account