lunedì 19 settembre 2011

Extremely Simple PHP Unit Test Framework [ENG]

Ok, I know. There is PHPUnit, already, and enough good books to get you started if you want to go down that path (that is the sensible thing to do, by the way).

Since I had to play with PHP for a pet project, got stuck with PHP4, was not able to set up PHPUnit and lost my patience, I decided to whip up something on my own. ESP-UTF is just an experiment: I wanted to peek behind the curtains to see how a unit test framework is made. Hope you may find something interesting among this crap.

First of all I only knew how to send the output of PHP scripts to a web page, so that's how I thought to show the test outcome.

How will the test cases look like? Well something like this:

class TestLanguage extends Test
{

 function testLanguageUK()
 {
  $pLang = new phpI18N('en');
   $testResult = $pLang->getPhrase('register', 'first_name');
  $this->assertEquals('First Name', $testResult);
 }

}

As in JUnit 3 I need to extend a basic Test class, and the test method has to be called testName. Since that's exactly what you have to do in Groovy I can live with that.

Now, how do I create a test runner? I did not want to do anything complicated, just a simple report. And I wanted my framework to handle test suites. Here's how I did that:

$testSuite = array(
 "TestDAOArticoli",
 "TestDAOUtente",
 "TestDAOCategoria",
 "TestLanguage",
 "TestCart"
);

$testResults = doTestSuite($testSuite);

render($testResults);

Could there be anything simpler? How do I load the test methods from each class?

function doTestSuite($testSuite)
{
 $testResults = array();
 foreach($testSuite as $testClass)
 {
  $testResults = array_merge($testResults, doTests($testClass));
 }
 return $testResults;
}

I collect the test results in an array. The render function will display that in a fancy style. Here's the doTests() method (more interesting):

function doTests($testClassName)
{
 $testResults = array();
 $class_methods = get_class_methods($testClassName);
 foreach ($class_methods as $method_name) 
 {
     if (preg_match("/^test/", $method_name))
     {
          $testResults[] = doTest($testClassName, $method_name);
     }
 }
 return $testResults;
}

No rocket science, so far, right? In the next episode: how to do the test?

Nessun commento: