Data Providers

Sometimes tests need to make the same assertions over many different types of data. Using #[DataProvider] can help reduce the amount of test duplication when you encounter this scenario.

When a test needs to make the same assertion across a variety of data a data provider can reduce the amount of duplication necessary to write the appropriate tests. A data provider is a public method on the TestCase that returns an array of arrays with the appropriate arguments for the test. The test needing to use the data provider should be annotated with the #[DataProvider] Attribute and define parameters on its method signature.

<?php

use Cspray\Labrador\AsyncUnit\TestCase;
use Cspray\Labrador\AsyncUnit\Attribute\Test;
use Cspray\Labrador\AsyncUnit\Attribute\DataProvider;

class MyDataProviderTestCase extends TestCase {

    public function myData() : array {
        return [
            ['async unit', 'phpunit'],
            ['AsyncUnit', 'AsyncUnit'],
            ['AsyncUnit', 'async unit']
        ];
    }

    #[Test]
    #[DataProvider('myData')]
    public function checkStringsAreEqual(string $expected, string $actual) : void {
        $this->assert()->stringEquals($expected, $actual);
    }

}

Each set of arguments will have its own TestCase instance and will have all of the appropriate test hooks invoked.

Last updated