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 skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to use hooks in PHPUnit?
- What are PHPUnit required extensions
- How to use the PHPUnit Framework TestCase?
- How to run PHPUnit in quiet mode?
- How to show warnings in PHPUnit?
- How to load fixtures with PHPUnit?
- How to use a listener with PHPUnit?
- How to stop PHPUnit on failure?
See more codes...