I'm trying to write a Unit Test in Magento 2 which uses a variable defined in __construct()
. The variable gets its value in another function. Thus when I run my test it gives me an error that the variable is null. How can I feed a value to that variable in my test to make it pass?
1 Answer
In unit tests you test components isolated. That means that you should construct the objects under test yourself and provide input by the test, not by some external method.
Example:
/**
* @dataProvider dataAddTwoNumbers
*/
public function testItAddsTwoNumbers($number1, $number2, $expectedResult)
{
$addition = new Addition($number1, $number2);
$this->assertEquals($expectedResult, $addition->result());
}
public static function dataAddTwoNumbers()
{
return [
[1, 1, 2],
[1, 0, 1],
[0, 1, 1],
[-1, 1, 0],
];
}
If you need other classes that would be instantiated by the object manager, instantiate them yourself, or create a stub/mock. Let's say, your Addition
class needs the StoreManagerInterface
and calls getStore()
on it (for whatever reason), then the code could look like this:
$store = $this->getMockBuilder(\Magento\Store\Api\Data\StoreInterface::class)
->getMockForAbstractClass();
$storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class)
->setMethods(['getStore'])
->getMockForAbstractClass();
$storemanager->method('getStore')->willReturn($store);
$addition = new Addition($storeManager, $number1, $number2);
If you want to test that it gets the right values and interacts correctly with the framework or other components, write an integration test, this is not the job of the unit test.