One possible solution for test packaging is to bundle your tests directly into your libraries. Because you are a tidy programmer, you keep all your functions in subordinate libraries. These libraries are never called directly (that is, you never create the page http://www.omniti.com/EmailAddress.inc). Thus, if you add your testing code so that it is run if and only if the library is called directly, you have a transparent way of bundling your test code directly into the code base. To the bottom of EmailAddress.inc you can add this block: if(realpath($_SERVER['PHP_SELF']) == _ _FILE_ _) {
require_once "PHPUnit/Framework/TestSuite.php";
require_once "PHPUnit/TextUI/TestRunner.php";
class EmailAddressTestCase extends
What is happening here? The top of this block checks to see whether you are executing this file directly or as an include. $_SERVER['PHP_SELF'] is an automatic variable that gives the name of the script being executed. realpath($_SERVER[PHP_SELF]) returns the canonical absolute path for that file, and _ _FILE_ _ is a autodefined constant that returns the canonical name of the current file. If _ _FILE_ _ and realpath($_SERVER[PHP_SELF]) are equal, it means that this file was called directly; if they are different, then this file was called as an include. Below that is the standard unit testing code, and then the tests are defined, registered, and run.
To test the EmailAddress class, you simply execute the include directly: (george@maya)[chapter-6]> php EmailAddress.inc PHPUnit 1.0.0-dev by Sebastian Bergmann. .. Time: 0.003005027771 OK (2 tests) This particular strategy of embedding testing code directly into the library might look familiar to Python programmers because the Python standard library uses this testing strategy extensively. Inlining tests has a number of positive benefits:
It has some drawbacks, as well:
Please check back next week for the continuation of this article. |