When you write tests in PHPUnit 11 you might run into the following message:
From PHPUnit 12 and onwards using doc block annotations will not work anymore and needs to be replaced with PHP Attributes.
Since PHP 8 we can use attributes to add annotations, methods and variables to methods in a structured way.
Untill PHPUnit 11 we can use the following code to use dataProviders in phpunit tests:
class SomethingTest extends TestCase
{
/**
* @dataProvider dataSomething
*/
public function testSomething(string $variable, string $expected): void
{
$this->assertEquals($expected, $variable);
}
public static function dataSomething(): array
{
return [
[
'value' => 'input',
'expected' => 'output',
]
];
}
}
The above example will not work anymore in PHPUnit 8.
The following example is the correct way of adding a dataprovider in PHPUnit 12:
use PHPUnit\Framework\Attributes\DataProvider;
class SomethingTest extends TestCase
{
#[DataProvider('dataSomething')]
public function testSomething(string $variable, string $expected): void
{
$this->assertEquals($expected, $variable);
}
public static function dataSomething(): array
{
return [
[
'value' => 'input',
'expected' => 'output',
]
];
}
}
Data providers are way to execute the same test with different data sets, without the need to create a new test for every scenarios.
Once a unit test and data provider are created, it makes it a lot easier to add new scenarios for the same type of tests.
Lets take a simple example of calculating VAT for a product.