Martijn van Nieuwenhoven

How to use Data Providers in PHPUnit 12

When you write tests in PHPUnit 11 you might run into the following message:

Metadata in doc-comments is deprecated and will no longer be supported in PHPUnit 12. Update your test code to use attributes instead.

From PHPUnit 12 and onwards using doc block annotations will not work anymore and needs to be replaced with PHP Attributes.

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

Data Providers with PHP Attributes in PHPUnit 12

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