0

I have 2 different data providers and i want to use the data from both the data providers for my testcase.

I did an array merge in the dataProviders section as

  public function provider_data() {

    $data1 = $this->getData('home_data');

    $data2= $this->getData('data2');

   $newarray = array_merge($data1, $data2);

    return $newarray;
}

But i see my test case is getting executed twice and i noticed that the test case actually executes for each array (Data1 and Data2) seperately though they were merged. What am i doing wrong here? How should i combine 2 data providers (Both the data providers have complete different format of the input data)

user3920295
  • 889
  • 2
  • 13
  • 31
  • Possible duplicate of [Can phpunit use multiple data provider](https://stackoverflow.com/questions/15125437/can-phpunit-use-multiple-data-provider) – Potherca Sep 19 '17 at 10:19

2 Answers2

2

You are going to need to do something more in depth than just a simple array_merge. The data provider provides an array of which each entry is an individual test case. Each test case is an array containing the arguments. Like so:

'testCase 1' => array(
     0 => argument 1,
     1 => argument 2
 ),
 'testCase 2' => array(
     0 => argument 1,
     1 => argument 2
 ),

Since you said that you test is being run twice each data provider must be providing only one entry. array_merge appends the second data provider array to your first array making two test cases. If you want to combine the data provided by each data provider you will need to do something like the following:

public function provider_data() {
    $data1 = $this->getData('home_data');
    $data2 = $this->getData('data2');

    $testCases = array();

    foreach ($data1 as $key => $arguments) {
        $testCases[] = array_merge($arguments, $data2[$key]);
    }

    return $testCases;
}

This takes the arguments from the second set of data and appends it to the arguments in the first. Now your test will receive the combined arguments from both data providers.

This assumes that both data arrays are the same length. If they may not be, you will need to add some logic for handling that case. Also keep in mind for the list of arguments, PHPUnit does not reference the keys for matching the arguments to the variable. It is only based on the order of the values in the array. So be careful with the arguments in your test case with this.

Schleis
  • 41,516
  • 7
  • 68
  • 87
0

I thought I will post this answer as well for trying to merge 2 arrays with differnt lengths. I used this logic

    $data1 = $this->loadData('data1');
    $data2 = $this->loadData('data2');
    $newarray = array();
    foreach($data1 as $key1 => $value1){
        foreach ($data2 as $key2 => $value2) {
            $newarray[] = array_merge($value2, $data1[$key1]);   
        }
    } 
return $newarray;
user3920295
  • 889
  • 2
  • 13
  • 31