Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data provider to setUp() in PHPUnit

Tags:

I'm currently trying to pass data from my data provider to the setUp()-method in PHPUnit.

Background: I am using PHPUnit for running frontend-tests in different browsers. The browser should be defined inside the data provider and needs to be known by the setUp()-method.

I understand, that a data provider initially is executed before the setUp()-method (as setUpBeforeClass()) is called. Therefore setUp()-data can not be passed to a data provider. But it should work the other way round, shouldn't it?

Does PHPUnit generate its own temporarily testclasses with data from the data provider "integrated"?

Of course: a workaround could be, to read the XML-file in the setUp()-method again. But that's the last option, I'd consider...

EDIT: Provided a small snippet:

part of dataProvider():

public function dataProvider()
{
    $this->xmlCnf = $data['config'];
    var_dump($this->xmlCnf); // array with config is exposed
    // [...]
}

And the setUp()-method:

 protected function setUp()
{
    var_dump($this->xmlCnf); // NULL
    //[...]
}
like image 508
Felix Avatar asked Nov 03 '16 09:11

Felix


1 Answers

In case this is useful to anyone:

The following code should work:

public function dataProvider()
{
    return [ [ /* dataset 1 */] , ... ]
}

protected setUp() {
    parent::setUp();
    $arguments = $this->getProvidedData();
    // $arguments should match the provided arguments for this test case
}

/** 
 * @dataProvider dataProvider
 */
public function testCase(...$arguments) {

}

The getProvidedData method seems to have been available since PHPUnit 5.6 (which was either shortly before or after this question was originally asked)

like image 70
apokryfos Avatar answered Sep 26 '22 16:09

apokryfos