How to mock a Context object
You can test your class like this:
public function testSomething()
{
$contextMock = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class)
->disableOriginalConstructor()
->getMock();
$productImageFactoryMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\ImageFactory::class)
->disableOriginalConstructor()
->getMock();
$assetRepoMock = $this->getMockBuilder(\Magento\Framework\View\Asset\Repository::class)
->disableOriginalConstructor()
->getMock();
$viewConfigMock = $this->getMockBuilder(\Magento\Framework\View\ConfigInterface::class)
->disableOriginalConstructor()
->getMock();
$productRepoMock = $this->getMockBuilder(\Magento\Catalog\Model\ProductRepository::class)
->disableOriginalConstructor()
->getMock();
$productImageMock = $this->getMockBuilder(\Magento\Catalog\Model\Product\Image::class)
->disableOriginalConstructor()
->getMock();
//mock here any methods you need to mock
$productImageFactoryMock->method('create')->willReturn($productImageMock);
$model = new \The\Class\You\Want\To\Test(
$contextMock,
$productImageFactoryMock,
$assetRepoMock,
$viewConfigMock,
$productRepoMock
);
//do asserts here
}
You can move all the mock building to the setUp()
method if you need to do more than 1 test.
The following code will create a mock of the context in your test.
$contextMock = $this->getMockBuilder(\Magento\Framework\App\Helper\Context::class)
->disableOriginalConstructor()
->getMock();
From: vendor/magento/module-sales/Test/Unit/Helper/DataTest.php:setup()
You then will need to use the pass the $contextMock
via the the object manager:
$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$objectToTest = $objectManager->getObject(
\Magento\Class\To\Test::class, [
'context' => $contextMock,
...
]
);
Or you can use a Mock and pass the argument if you need need to change the method output of the class you are changing:
$objectToTest = $this->getMockBuilder(\Magento\Class\To\Test::class)
->setConstructorArgs([
'context' => $contextMock
])->getMock();