Dynamically create PHPUnit tests from a data file

I have a data file with input and expected outputs. An example would be:

input: output: 2 3 3 5 4 Exception 5 8 ... ... 

I currently have a special solution for reading from a data file and running a test for each pair of {input, output}. I would like to convert this to a PHPUnit-based solution, and I would like to have one test per input, using the test name forXassertY. So, the first three tests will be called for2assert3 (), for3assert5 () and for4assertException ().

I do not want to convert my existing data into tests if you can dynamically create test methods and store the data file as the basis of these tests. I want to convert it to PHPUnit, as I want to add some other tests later, and also process and view the output using Hudson.

Suggestions?

+7
php phpunit
source share
2 answers

You can use PHPUnit data providers to do this:

 <?php require_once 'PHPUnit/Framework/TestCase.php'; class ProviderTest extends PHPUnit_Framework_TestCase { public function testCaseProvider() { // parse your data file however you want $data = array(); foreach (file('test_data.txt') as $line) { $data[] = explode("\t", trim($line)); } return $data; } /** * @dataProvider testCaseProvider */ public function testAddition($num1, $num2, $expectedResult) { $this->assertEquals($expectedResult, $num1 + $num2); } } ?> 

and your test_data.txt file looks something like this:

 1 2 3 2 2 4 3 5 7 

Then run the test:

 $ phpunit ProviderTest.php PHPUnit 3.4.12 by Sebastian Bergmann. ...F Time: 0 seconds, Memory: 5.75Mb There was 1 failure: 1) ProviderTest::testAddition with data set #2 ('3', '5', '7') Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -7 +8 /Users/dana/ProviderTest.php:23 FAILURES! Tests: 4, Assertions: 3, Failures: 1. 
+10
source share

Well, PHP files are just text files, so you can write a TestGenerator.php script that will read in the data file and throw out a bunch of test .php files. The script test generator will be as simple as "read a line, parse it, spit out PHP". Then just run this test script generator as part of the build / test process and you're good to go.

0
source share

All Articles