Separate data provider from test case class
Asked Answered
C

3

11

I want to use PHPUnit to test my PHP class.

Is it possible to put data providers for my test methods in a separate file created only for storing dataproviders? If so how to do that?

Another question is whether it's a good practice or perhaps it's better to keep test and data provider methods in the same test class.

Cordeelia answered 4/6, 2017 at 9:47 Comment(0)
M
19

Simply use @dataProvider class::method to use a method from a different class than the test case class as a data provider for a test.

Mhd answered 4/6, 2017 at 15:35 Comment(1)
Note that it works only with the fully qualified name of the class in the annotation, like @dataProvider \App\Tests\MyProvider::method() as explained in this other response.Sowell
N
6

In Laravel 5.7, I've used:

From Tests:

@dataProvider \App\Tests\DataProviders\ClassNameDataProvider::dataMethodName()

From ClassNameDataProvider:

public static function dataMethodName(): array
    {
        return [
            [
                'input',
                'output',
            ],
         ]
     }
Numerator answered 26/6, 2019 at 9:47 Comment(0)
U
4

In phpunit 10 (requires PHP 8.1 or above) you can do this using an attribute:

use PHPUnit\Framework\Attributes\DataProviderExternal;

#[DataProviderExternal(\Tests\DataProvider::class, 'dataProviderMethod')]
public function test_data_provider_from_external_class(string $data): void
{
    // ...
}

Which would correspond to this class and method:

class DataProvider
{
    public static function dataProviderMethod(): array
    {
        // ...
    }
}

Uriisa answered 7/9, 2023 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.