phpunitHow to use a data provider in PHPUnit?
Data providers are a powerful feature of PHPUnit that allow you to pass multiple sets of data to a test method.
<?php
class DataProviderTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider additionProvider
*/
public function testAdd($a, $b, $expected)
{
$this->assertSame($expected, $a + $b);
}
public function additionProvider()
{
return [
'adding zeros' => [0, 0, 0],
'zero plus one' => [0, 1, 1],
'one plus zero' => [1, 0, 1],
'one plus one' => [1, 1, 2]
];
}
}
The output of the example code is:
OK (4 tests, 4 assertions)
Code explanation
@dataProvider additionProvider
- This annotation tells PHPUnit to use theadditionProvider
method as a data provider for the test method.public function additionProvider()
- This method returns an array of data sets to be used in the test method.$this->assertSame($expected, $a + $b);
- This assertion checks that the expected result matches the actual result of the addition.
Helpful links
More of Phpunit
- How to show warnings in PHPUnit?
- How to stop PHPUnit on failure?
- How to skip a PHPUnit test?
- How to use the PHPUnit Framework TestCase?
- How to ignore a test in PHPUnit?
- How to use getMockBuilder with PHPUnit?
- How to use dependency injection in PHPUnit?
- How to generate a coverage report with PHPUnit?
- How to run all PHPUnit tests?
- How to install PHPUnit with a PHAR file?
See more codes...