What is the difference between createMock and getMockBuilder in phpUnit?

2022-08-30 13:16:26

For the love of my life I can't figure out the difference between and createMock($type)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.


答案 1

createMock($type) uses internally:getMockBuilder()

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

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

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


答案 2

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.


推荐