Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array as an argument from providers in PHPUnit?

Tags:

php

phpunit

I have a test method that receives an array as an argument, and I want to feed the data from a data provider method?

how can that be achieved?

public function dataProvider(){
        return array(array(
                'id'=>1,
                'description'=>'',
        ));
}

/**
 * @dataProvider dataProvider
 */
public function testAddDocument($data){
// data here shall be an array provided by the data provider
// some test data here
}

What happens is that it passes the value of 'id' key ...etc

I want to pass the whole array

like image 325
Omar S. Avatar asked Aug 06 '12 19:08

Omar S.


1 Answers

Data provider methods must return an array containing one array for each set of arguments to pass to the test method. To pass an array, include it with the other arguments. Note that in your sample code you'll need another enclosing array.

Here's an example that returns two sets of data, each with two arguments (an array and a string).

public function dataProvider() {
    return array(                       // data sets
        array(                          // data set 0
            array(                      // first argument
                'id' => 1,
                'description' => 'this',
            ),
            'foo',                      // second argument
        ),
        array(                          // data set 1
            array(                      // first argument
                'id' => 2,
                'description' => 'that',
            ),
            'bar',                      // second argument
        ),
    );
}

Important: Data provider methods must be non-static. PHPUnit instantiates the test case to call each data provider method.

like image 110
David Harkness Avatar answered Oct 05 '22 00:10

David Harkness