Test with multiple data using PHPUnit
Question:
How to test with multiple data using PHPUnit? Answer:
/**
* @dataProvider dateProvider
*/
public function testGetLastDayOfTheMonth($in, $expected)
{
$lastDay = DateHelper::getLastDayOfTheMonth($in);
self::assertEquals($expected, $lastDay);
}
public function dateProvider(): array
{
return [
['2021-01-17', '2021-01-31'],
['2021-02-17', '2021-02-28'],
['2021-03-01', '2021-03-31'],
['2021-04-27', '2021-04-30'],
];
}
Description:
In cases when you want to test your code with different input values data providers can help.
A test method can accept arbitrary arguments. These arguments are to be provided by a data provider method. The data provider method to be used is specified using the @dataProvider
annotation.
A data provider method must be public
and either return an array of arrays or an object that implements the Iterator interface and yields an array for each iteration step. For each array that is part of the collection, the test method will be called with the contents of the array as its arguments.
Reference:
PHPUnit data provider reference
Share "How to test with multiple data using PHPUnit?"
Related snippets:
Tags:
test multiple dataset, phpunit data provider, using data provider Technical term:
Test with multiple data using PHPUnit