Main Content

How to build a test harness into your PHP

Archive - Originally posted on "The Horse's Mouth" - 2010-03-16 06:47:17 - Graham Ellis

I was writing a PHP demonstration yesterday, and I wanted to include a test harness with my class definitions that I could leave in place on the live code on my server, to be silently skipped over ... but which I could re-use at a later date for testing class changes, etc.

How did I do it? An environment variable, which I need to provide in order for the test harness to be run. My PHP code contains

if ($_ENV["TESTING"]) {
  # Test environment - run the file
  # On a production run this will be skipped!
  # Test code here
}


And it runs like this:

Dorothy-2:sj grahamellis$ php staticmember.php
Dorothy-2:sj grahamellis$ export TESTING=1
Dorothy-2:sj grahamellis$ php staticmember.php
Service leaves at 05:19
Service leaves at 16:39
Service leaves at 07:02
Service leaves at 17:02
The next service will have id 5
Dorothy-2:sj grahamellis$