📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing Data Providers

Data Providers

5 min read Quiz at the end
Run the same test with many inputs using @dataProvider — eliminate duplicate test methods.

Data Providers

class MathTest extends TestCase {
    /**
     * @dataProvider additionProvider
     */
    public function testAdd(int $a, int $b, int $expected): void {
        $this->assertEquals($expected, (new Calculator)->add($a, $b));
    }

    public static function additionProvider(): array {
        return [
            "positive numbers" => [1,  2,  3],
            "negative numbers" => [-1, -2, -3],
            "mixed"            => [-1,  2,  1],
            "zeros"            => [0,   0,  0],
        ];
    }

    // PHP 8 attribute syntax
    #[DataProvider("squaresProvider")]
    public function testSquare(int $n, int $expected): void {
        $this->assertEquals($expected, $n ** 2);
    }

    public static function squaresProvider(): array {
        return [[2, 4], [3, 9], [4, 16], [0, 0]];
    }
}
Topic Quiz · 2 questions

Test your understanding before moving on

1. What does a data provider return?
💡 Data providers return arrays where each element is an array of arguments.
2. Data provider methods must be:
💡 Data provider methods must be public static.