Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'));
like image 801
Arnold Daniels Avatar asked Nov 14 '25 21:11

Arnold Daniels


1 Answers

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.

like image 94
Arnold Daniels Avatar answered Nov 17 '25 11:11

Arnold Daniels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!