Search code examples
phpattributesphpunit

Using separate data provider class with PHPUnit and attributes


I would like to separate Tests and Data Providers. Using PHP 8 attributes, I cannot get the following test to run when referencing an external Data Provider:

#[Test]
#[DataProviderExternal(RouterDataProvider::class, 'registerGetRouteData')]
public function itRegistersGetRoute(Route $route, array $expectedResult)
{
    $this->router->get($route);
    $this->assertEquals($expectedResult, $this->router->getRoutes());
}

My data provider class:

class RouterDataProvider
{
    public static function registerGetRouteData(): array
    {
        return [
            $route = new Route('/', ['IndexController', 'index']),
            [
                'GET' => [
                    '/' => $route,
                ],
                'POST' => []
            ]
        ];
    }
}

How could I get this test to run with the desired provider method?


Solution

  • By running PHPUnit with the following flags, I was able to see exactly what my issue was:

    ./vendor/bin/phpunit --display-deprecations --display-warnings --diplay-errors --display-notices
    

    The data set was invalid. Changing the return to yield and updating the return type for the registerGetRouteData method from array to \Generator resolved this.

    I was running phpunit with the --testdox flag, so I'm not sure if this is what stopped me seeing any errors initially and assume the test was being skipped.