phpunit avoid constructor arguments for mock

后端 未结 7 1086
有刺的猬
有刺的猬 2021-01-30 08:24

What is the way to avoid phpunit having to call the constructor for a mock object? Otherwise I would need a mock object as constructor argument, another one for that etc. The ap

7条回答
  •  借酒劲吻你
    2021-01-30 08:32

    This question is a little old, but for new visitors, you can do it using the createMock method (previously called createTestDouble and introduced in v5.4.0).

    $mock = $this->createMock($className);
    

    As you can see in the code below extracted from the PHPUnit\Framework\TestCase class (in phpunit/src/framework/TestCase.php), it will basically create a mock object without calling the original constructor.

    /** PHPUnit\Framework\TestCase::createMock method */
    protected function createMock(string $originalClassName): MockObject
    {
        return $this->getMockBuilder($originalClassName)
                    ->disableOriginalConstructor()
                    ->disableOriginalClone()
                    ->disableArgumentCloning()
                    ->disallowMockingUnknownTypes()
                    ->getMock();
    }
    

提交回复
热议问题