David762
David762

Reputation: 465

Separate data provider from test case class

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.

Upvotes: 11

Views: 3622

Answers (3)

D1__1
D1__1

Reputation: 1357

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
    {
        // ...
    }
}

Upvotes: 4

Mexidense
Mexidense

Reputation: 1181

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

Upvotes: 6

Sebastian Bergmann
Sebastian Bergmann

Reputation: 8326

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.

Upvotes: 19

Related Questions