3

Is it possible to have PHPUnit fail when any unconfigured method is called on a mock object?

Example;

$foo = $this->createMock(Foo::class);
$foo->expects($this->any())->method('hello')->with('world');

$foo->hello('world');
$foo->bye();

This test will succeed. I would like it to fail with

Foo::bye() was not expected to be called. 

P.S. The following would work, but this means I'd have to list all configured methods in the callback. That's not a suitable solution.

$foo->expects($this->never())
    ->method($this->callback(fn($method) => $method !== 'hello'));
Arnold Daniels
  • 16,516
  • 4
  • 53
  • 82
  • Does this answer your question? [PHPUnit Mock Objects never expect by default](https://stackoverflow.com/questions/13624938/phpunit-mock-objects-never-expect-by-default) – wazelin Jan 09 '20 at 11:30

1 Answers1

5

This is done by disabling auto-return value generation.

$foo = $this->getMockBuilder(Foo::class)
    ->disableAutoReturnValueGeneration()
    ->getMock();

$foo->expects($this->any())->method('hello')->with('world');

$foo->hello('world');
$foo->bye();

This will result in

Return value inference disabled and no expectation set up for Foo::bye()

Note that it's not required for other methods (like hello) to define a return method.

Arnold Daniels
  • 16,516
  • 4
  • 53
  • 82
  • This is an undocumented feature but can be found by looking at the source code of PHPUnit. https://github.com/sebastianbergmann/phpunit/blob/master/src/Framework/MockObject/InvocationHandler.php#L144 – Arnold Daniels Jan 09 '20 at 14:43