phpunit avoid constructor arguments for mock

后端 未结 7 1083
有刺的猬
有刺的猬 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:49

    You can use getMockBuilder instead of just getMock:

    $mock = $this->getMockBuilder('class_name')
        ->disableOriginalConstructor()
        ->getMock();
    

    See the section on "Test Doubles" in PHPUnit's documentation for details.

    Although you can do this, it's much better to not need to. You can refactor your code so instead of a concrete class (with a constructor) needing to be injected, you only depend upon an interface. This means you can mock or stub the interface without having to tell PHPUnit to modify the constructor behaviour.

提交回复
热议问题