1

I want to write unit test for a module which contains these functions:

public function abc($Str)
{
    $n = $this->def();
 ...
    return x;
}
public function def()
    {
 ...
        $productRepo= $this->productRepo->get($this->_product->getSku());
...
            return $something;
        }

I have alredy tried to mock a product and pass the sku value of it but every time it gives me this error:

PHP Fatal error:  Call to a member function getSku() on a non-object in...

Here is how I wrote mock for it:

$sku->method('getSku')->willReturn('sku-test');

I have also tried to mock it this way in my setUp() but still getting the error:

    protected function setUp()
{

    $sku = $this->getMockBuilder(\Magento\Catalog\Api\ProductRepositoryInterface::class)
        ->getMockForAbstractClass();
    $skuManager = $this->getMockBuilder(\Magento\Catalog\Api\Data\ProductInterface::class)
        ->setMethods(['getSku'])
        ->getMockForAbstractClass();
}

1 Answer 1

1

You assign the mock to a local variable $skuManager and then do nothing with it.

When instantiating your component under test, you have to pass the mock as constructor parameter in place of the real ProductRepository.

Note that you should not use the ObjectManager in unit tests to instantiate your component. Create or mock the dependencies explicitly instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.