PHPUnit Beginner Part 2: Data Provider

There's general rule that you shouldn't use loops in your test suites, but why use data providers? It creates cleaner tests and has more comprehensive errors. The following test is simple, but easily illustrates these points.

<?php

class ExampleTest extends PHPUnit_Framework_TestCase
{
    public function testA()
    {
        foreach ($this->exampleProvider() as $input) {
            list($expected, $actual) = $input;
            $this->assertEquals($expected, $actual);
        }
    }

    /**
     * @param string $expected The expected value of the test
     * @param string $actaul   The actual value of the test
     * @dataProvider exampleProvider
     */
    public function testB($expected, $actual)
    {
        $this->assertEquals($expected, $actual);
    }

    public function exampleProvider()
    {
        return [
            ['bar', 'bar'], ['fizz', 'buzz']
        ];
    }
}

TestB is far simpler to read the parameters are specified and easily understood. Yes, somebody new to phpunit would have to google "dataProvider". The error messages for these two identical tests are completely different:

$php vendor/bin/phpunit exampleTest.php
PHPUnit 4.3.5 by Sebastian Bergmann.

Configuration read from /phpunit.xml

F.F

Time: 38 ms, Memory: 4.75Mb

There were 2 failures:

1) ExampleTest::testA
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'fizz'
+'buzz'

/exampleTest.php:9

2) ExampleTest::testB with data set #1 ('fizz', 'buzz')
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'fizz'
+'buzz'

The important difference here is ExampleTest::testB with data set #1 ('fizz', 'buzz'). phpunit tells you the specific offset in the dataprovider that failed as well as the values supplied by that offset. In our contrived example it is easy to see which data set the error came from, but this is not always the case. By using data provider, your testcase became more readable and the error messages became more informative.

/r/PHP Thread Parent Link - startutorial.com