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]];
}
}