Bacchus Bacchus - 4 months ago 7
PHP Question

Property successfully set in provider overwritten as null in the test

After I successfully initialize property

mock
in provider(I do this because I want to pass the property as argument and if it is not initialize in the provider, an error occurs because the prop is null) and pass it to the test, I have a problem: the property is overwritten as null.

class Test extends \PHPUnit_Framework_TestCase
{
protected $mock;

/**
* @param $arg List of objects from DB
*
* @dataProvider providerTest
*/
public function test($arg)
{
var_dump($this->mock) // ---> NULL
}





public function providerTest()
{
$this->mock = $this->getMockBuilder(Currency::class)
->disableOriginalConstructor()
->getMock();

var_dump($this->mock) // -----> OBJECT

return array(
array('argument')
);
}
}

Answer

I assume that you want to know why this happens. The documentation of PHPUnit actually explains this:

Note

All data providers are executed before both the call to the setUpBeforeClass static method and the first call to the setUp method. Because of that you can't access any variables you create there from within a data provider. This is required in order for PHPUnit to be able to compute the total number of tests.

So you should either move the creation of the MockObject into the setUp() method or directly in the test method that uses the data provider:

class Test extends \PHPUnit_Framework_TestCase
{    
    protected $mock;

    protected function setUp()
    {
        $this->mock = $this->getMockBuilder(Currency::class)
            ->disableOriginalConstructor()
            ->getMock();
    }

    /**
     * @param $arg List of objects from DB     
     *
     * @dataProvider providerTest
     */
    public function test($arg)
    {
        var_dump($this->mock) // ---> MockObject
    }

    public function providerTest()
    {
        return array(           
            array('argument')
        );
    }
}