如何使phpunitmock在调用未配置的方法时失败?
当对模拟对象调用任何未配置的方法时,PHPUnit是否可能失败 榜样如何使phpunitmock在调用未配置的方法时失败?,php,mocking,phpunit,Php,Mocking,Phpunit,当对模拟对象调用任何未配置的方法时,PHPUnit是否可能失败 榜样 $foo = $this->createMock(Foo::class); $foo->expects($this->any())->method('hello')->with('world'); $foo->hello('world'); $foo->bye(); 这次试验会成功的。我希望它以失败告终 Foo::bye() was not expected to be calle
$foo = $this->createMock(Foo::class);
$foo->expects($this->any())->method('hello')->with('world');
$foo->hello('world');
$foo->bye();
这次试验会成功的。我希望它以失败告终
Foo::bye() was not expected to be called.
另外,下面的方法可以工作,但这意味着我必须在回调中列出所有配置的方法。这不是一个合适的解决方案
$foo->expects($this->never())
->method($this->callback(fn($method) => $method !== 'hello'));
这是通过禁用自动返回值生成来实现的
$foo = $this->getMockBuilder(Foo::class)
->disableAutoReturnValueGeneration()
->getMock();
$foo->expects($this->any())->method('hello')->with('world');
$foo->hello('world');
$foo->bye();
这将导致
Return value inference disabled and no expectation set up for Foo::bye()
请注意,其他方法(如
hello
)不需要定义返回方法。这是否回答了您的问题?这是一个未记录的特性,但是可以通过查看PHPUnit的源代码找到。