Search code examples
phpmockingphpunit

How to make PHPUnit mock fail on calling unconfigured methods?


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'));

Solution

  • 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.