I'm asked about data providers almost every time I introduce a developer to PHPUnit. Once you understand them, they're quite clear, but on first pass they seem to give developers pause.
So what are they? Practically, a data provider is any static method that produces an array of arrays. The outer array defines the iterations of the test loop, while the inner arrays are the arguments to pass to each iteration. Let's look at an example. First, annotate a test method's docblock:
/**
* @dataProvider provides_foo_and_bar
*/
public function test_frobnicator($foo, $bar) { /* ... */ }
Then define the data provider:
public static function provides_foo_and_bar() {
return [
[ 'FOO', 'BAR' ],
[ 'BAZ', 'QUUX' ],
];
}
PHPUnit will call provides_foo_and_bar
twice. The first time it will pass test_frobnicator
with "FOO" and "BAR". The second time it will call test_frobnicator
with "BAZ" and "QUUX". Note that the data provider is both public and static: PHPUnit requires that.
Pro-top: by default, phpunit runs all data sets. But, you can select specific data sets to run easily: phpunit FrobnicateModel.php test_frobnicate#1
runs only one loop, with the 1-index elements "BAZ" and "QUUX".