So I was wondering what a very easy-to-use Unit Tester might look like. My idea was to have something that was so easy-to-use that people who would not take the time to learn PHPUnit or SimpleTest might use it to create a little test coverage for their code. It also might be handy around there forums to have Unit Tester to use with code snippets. This gets more interesting when you use Unit Tests as the requirements/specification for code -- which is one of the best ways to use Unit Tests.
Here were my requirements:
- Did not require building test classes
- Only support/introduce the most basic "assert" cases
- Track the number of "passed" and "failed" tests
- Have a simple HTML Reporter to show either "passed" in green or list the file and line numbers of failed tests in red
So I wrote small Unit Tester that you could used like this:
Code: Select all
function doubler($number) {
return $number + $number;
}
include 'TinyTest.php';
$tester = new UnitTester();
// change these to incorrect values to see failed tests reported
$tester->assertTrue(doubler(2) == 4);
$tester->assertTrue(1 == 1);
$tester->assertFalse(1 == 2);
$reporter = new HTMLReporter();
$reporter->output($tester);Code: Select all
class UnitTester {
var $total_passed = 0;
var $total_failed = 0;
function TinyTest() {
}
function assertTrue($result) {
if ($result) {
$this->_testPassed();
} else {
$this->_testFailed();
}
}
function assertFalse($result) {
if ($result) {
$this->_testFailed();
} else {
$this->_testPassed();
}
}
function _testPassed() {
++$this->total_passed;
}
function _testFailed() {
++$this->total_failed;
$backtrace = debug_backtrace();
$this->failures[] = $backtrace[1];
}
}
class HTMLReporter {
var $passed_heading_style = 'color: white; background-color: green; margin-top: 2; padding: 4 4 4 4;';
var $failed_heading_style = 'color: white; background-color: red; margin-top: 2; padding: 4 4 4 4;';
var $failed_test_style = 'color: white; background-color: red; margin-top: 2; padding-left: 4;';
function output($test) {
if ($test->total_failed > 0) {
echo '<div style="' . $this->failed_heading_style . '">Failed ' . $test->total_failed . ' of ' . ($test->total_failed + $test->total_passed) . ' tests. </div>';
$n = 1;
foreach ($test->failures as $backtrace) {
$message = $n++ . ". Failed: {$backtrace['function']} on line {$backtrace['line']} of file {$backtrace['file']}. ";
echo '<div style="' . $this->failed_test_style . '">' . $message . '</div>';
}
} else {
echo '<div style="' . $this->passed_heading_style . '">Passed ' .$test->total_passed . ' tests.</div>';
}
}
}So, is this enough to be useful or are there other features that even the most basic Unit Tester must have? Is this interesting or worthwhile?