phpunit avoid constructor arguments for mock

Koen picture Koen · Nov 11, 2008 · Viewed 57.6k times · Source

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 api seems to be like this:

getMock($className, $methods = array(), array $arguments = array(),
        $mockClassName = '', $callOriginalConstructor = TRUE,
        $callOriginalClone = TRUE, $callAutoload = TRUE)

I don't get it to work. It still complains about the constructor argument, even with $callOriginalConstructor set to false.

I only have one object in the constructor and it is a dependency injection. So I don't think I have a design problem there.

Answer

dave1010 picture dave1010 · Jun 8, 2011

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.