PHPUnit Data Providers

A function/method can accept unpredictable arguments. In order to test large number of arguments efficiently and quick. PHPUnit provides the @dataProvider annotation.

The @dataProvider method you provide, must be public and either return an array of arrays or an object that implements the Iterator interface. PHPUnit will call each array element as arguments to the test method. The code below as well shows an example in which it reads a csv file in a php class. The php class implements the Iterator interface.

use PHPUnit\Framework\TestCase;

class AddTest extends TestCase
{
    /**
     * @dataProvider testProvider
     */
    public function testAdd($a, $b, $expected): void
    {
        $this->assertSame($expected, $someTestObject->add($a, $b));
    }
        
    /**
     * @dataProvider csvProvider
     */
    public function testAddWithCsvFileImplementingIteratorInterface($a, $b, $expected): void
    {
        $this->assertSame($expected, $someTestObject->add($a, $b));
    }

    /*
     * @note: This must be public
     */
    public function testProvider(): array
    {
        return [
            [0, 0, 0],
            [0, 2, 2],
            [1, 0, 1],
            [1, 2, 3]
        ];
    }

    public function csvProvider(): Iterator
    {
        return new CsvFileIterator('somefile.csv');
    }
}
what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news

Articles

PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.