mercoledì 21 settembre 2011

Extremely Simple PHP Unit Test Framework/2 [ENG]

How does ESP-UTF (see part 1) run the single test?

function doTest($testClassName, $testMethodName)
{
 global $testFailed;
 global $testFailedCause;
 $testFailedCause = "";
 $testFailed = false;
 
 $object = new $testClassName();
 $object->$testMethodName();
 
 $result = new TestResult($testClassName, $testMethodName, !$testFailed, $testFailedCause);
 
 return $result;
}

Things to note here:

  • the test result is held by a pair of global variables (lines 3 and 4); that's how I handled the errors; more on that later
  • strings can be used as class and methods names without further ado (lines 8 and 9)
  • the result is returned as a TestResult object

I did not know how to trap errors (did I already say that I'm stuck with PHP4 and no exception handling?) other than by setting an error handler:

set_error_handler ('errorHandler');

function errorHandler($errno, $errstr, $errfile, $errline)
{
 global $testFailed;
 global $testFailedCause;
 $testFailedCause = "\nError: " . $errno . ", file: " . $errfile . "; line: " . $errline . "; error: ". $errstr . "";
 $testFailed = true;
 return true;
}

There's catch of course: if an assertion fails the execution of the method does not get stopped, it just goes on through to the end because that's how the error handler's supposed to work. Since I consider that a minor annoyance I did not waste further effort trying to mend that.

Here's the TestResult class:

class TestResult
{
 var $testClassName;
 var $testMethodName;
 var $testBooleanResult;
 var $testMessageResult;
 
 function TestResult($className, $methodName, $booleanResult, $messageResult)
 {
  $this->testClassName = $className;
  $this->testMethodName = $methodName;
  $this->testBooleanResult = $booleanResult;
  $this->testMessageResult = $messageResult;
 }
 
 function x()
 {
  return $this->testClassName . "." . $this->testClassMethod . "='" . $this->testMessageResult . "'";
 }
 
}

Nothing fancy, in fact.

In the next episode the Test class

Nessun commento: