Php – Dynamically create PHPUnit tests from data-file

PHPphpunit

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

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

Currently I have a custom solution to read from the data file and perform a test for each {input,output} pair. I would like to convert this into a PHPUnit based solution and I would like to have one test per input using the test name forXassertY. So the first three tests would be called for2assert3(), for3assert5() and for4assertException().

I do not want to convert my existing data to tests if it's possible to create the test methods dynamically and keep 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 on and also process and view the output using Hudson.

Suggestions?

Best Answer

You can use PHPUnit's data providers for 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.