Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between createMock and getMockBuilder in phpUnit?

Tags:

php

phpunit

For the love of my life I can't figure out the difference between createMock($type) and getMockBuilder($type)

I am going through the original documentation and there is just a one liner which I didn't understand.

... you can use the getMockBuilder($type) method to customize the test double generation using a fluent interface.

If you can provide me an example, I would be grateful. Thanks.

like image 427
Chris Roy Avatar asked Jul 13 '16 23:07

Chris Roy


People also ask

What is mocking in PHPUnit?

Likewise, PHPUnit mock object is a simulated object that performs the behavior of a part of the application that is required in the unit test. The developers control the mock object by defining the pre-computed results on the actions.

What is createPartialMock?

createPartialMock(Class<T> type, String... methodNames) A utility method that may be used to mock several methods in an easy way (by just passing in the method names of the method you wish to mock). static <T> T. createPartialMock(Class<T> type, String[] methodNames, Object...


2 Answers

createMock($type) uses getMockBuilder() internally:

protected function createMock($originalClassName) {     return $this->getMockBuilder($originalClassName)                 ->disableOriginalConstructor()                 ->disableOriginalClone()                 ->disableArgumentCloning()                 ->disallowMockingUnknownTypes()                 ->getMock(); } 

So the createMock() method will return you a mock built with the general best-practice defaults.

But with getMockBuilder($type), you can create a mock with your own requirements.

like image 195
Gautam Rai Avatar answered Sep 30 '22 17:09

Gautam Rai


From the manual https://phpunit.de/manual/current/en/test-doubles.html

The createMock($type) and getMockBuilder($type) methods provided by PHPUnit can be used in a test to automatically generate an object that can act as a test double for the specified original type (interface or class name). This test double object can be used in every context where an object of the original type is expected or required.

The createMock($type) method immediately returns a test double object for the specified type (interface or class). The creation of this test double is performed using best practice defaults (the __construct() and __clone() methods of the original class are not executed and the arguments passed to a method of the test double will not be cloned.

If these defaults are not what you need then you can use the getMockBuilder($type) method to customize the test double generation using a fluent interface.

They are already plenty answers on stack overflow what are fluent interfaces.

like image 20
Pawel Wodzicki Avatar answered Sep 30 '22 18:09

Pawel Wodzicki