pTest: PHP Unit Tester in 9 Lines Of Code

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().

Replay

Category: programming Time: 2007-08-13 Views: 1
Tags:

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.155 (s). 12 q(s)