Back to results for “Unit Testing with PHPUnit”
PHP › Unit Testing with PHPUnit

How do data providers in PHPUnit let you run the exact same test logic repeatedly against many different sets of input data, without duplicating the test method itself?

Advanced

Answer

A data provider is a separate method that returns a collection of different input and expected output combinations, and by associating a test method with a data provider, PHPUnit will automatically run that same single test method once for every individual data set the provider returns, which avoids writing many nearly identical, separate test methods that only differ in their specific input values, and makes it very easy to thoroughly test a piece of logic against a wide range of different scenarios, including various edge cases, all through one single, reusable test method.
public function additionProvider(): array
{
    return [[1, 1, 2], [2, 3, 5], [-1, 1, 0]];
}

/** @dataProvider additionProvider */
public function testAdd(int $a, int $b, int $expected): void
{
    $this->assertEquals($expected, (new Calculator())->add($a, $b));
}
Real-world example A test verifying an addition method uses a data provider supplying several different pairs of numbers along with their correctly expected sums, running the exact same underlying test logic automatically against each individual data set without needing to write several nearly duplicate test methods.

Common follow-ups: Can a data provider itself depend on external data, such as reading from a file?;How does PHPUnit report a failure when only one specific data set within a data provider actually fails?