PHPUnit mock missing functions in a class or interface

When writing unit tests, sometimes we mock classes or interfaces which have certain functions which are missing. This happens a lot during my development with magento. In such a scenario PHPUnit gives you the possibility to provide function name(s) for that interface or class. You can use Partial mocks or use getMockBuilder to mock the class and the missing function properly.

Using Partial Mock the code will look as below.

We are creating mock of interface 'AddressInterface' and we are telling that it has a function called 'setShippingAddress'

$mock = $this->createPartialMock(
    \Magento\Quote\Api\Data\AddressInterface::class,
    ['setShippingAddress']
);

If you are using the function getMockBuilder the code will look as below.

Here we are creating instance of class 'SomeFactory' and it had a function called ‘create’

$mockFactory = $this->getMockBuilder('\Magento\Sales\Model\Order\SomeFactory')
->disableOriginalConstructor())
->setMethods(['create']))
->getMock();
what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news

Articles

PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.