O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #80. Generate Your Unit Tests

Use PHP to build your unit tests from code comments.

Unit tests [Hack #79] are so critical to the development of a stable application that it's worth going to some effort to create them. However, there's some nice middle ground between writing unit tests completely by hand (including the routine portion of those tests that is the same, over and over again), and automating test creation. This hack shows how to use a script to generate unit test code from comments embedded in your PHP code. The comments are test specific, but this does cut down on the redundant code you have to type in.

The Code

Save the code in Example 8-3 as Add.php. Note that several tests are laid out using the == and != operators all in the PHP script comments.

Example 8-3. The code from which to build unit tests

<?php
// UNIT_TEST_START
// ( 1, 2 ) == 3
// ( 1, -1 ) == 0
// ( 1, 1 ) != 3
// ( 1, -1 ) != 1
// UNIT_TEST_END
function add( $a, $b ) { return $a + $b; }

// UNIT_TEST_START
// ( 1, 2 ) == -1
// ( 1, -1 ) == 2
// ( 1, 1 ) != 1
// ( 1, -1 ) != 1
// UNIT_TEST_END
function minus( $a, $b ) { return $a - $b; }
?>

Save the code in Example 8-4 as GenUnit.php. This script handles generation of tests from another script's comments.

Example 8-4. The unit test generator

<?php if ( count( $argv ) < 2 ) { print "GenUnit.php usage:\n"; print " php GenUnit.php <PHP Script>\n"; exit; } $infile = $argv[1]; define( 'STATE_NORMAL', 0 ); define( 'STATE_IN_UNIT_DEF', 1 ); define( 'STATE_WAITING_FOR_FUNC', ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required