10

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.

Sebastian Bergmann
  • 7,837
  • 1
  • 27
  • 35
David762
  • 455
  • 4
  • 20

2 Answers2

16

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.

Sebastian Bergmann
  • 7,837
  • 1
  • 27
  • 35
  • 4
    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](https://stackoverflow.com/questions/45866365/how-can-i-reference-external-data-providers-in-phpunit). – Olivier Maurel Sep 05 '18 at 05:50
5

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',
            ],
         ]
     }
Mexidense
  • 954
  • 8
  • 7