【问题标题】:How to make PHPUnit mock fail on calling unconfigured methods?如何使 PHPUnit 模拟在调用未配置的方法时失败?
【发布时间】:2020-04-26 23:10:27
【问题描述】:

在模拟对象上调用任何未配置的方法时是否可能导致 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 called. 

附:以下方法可行,但这意味着我必须在回调中列出所有配置的方法。这不是一个合适的解决方案。

$foo->expects($this->never())
    ->method($this->callback(fn($method) => $method !== 'hello'));

【问题讨论】:

标签: php mocking phpunit


【解决方案1】:

这是通过禁用自动返回值生成来完成的。

$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)不需要定义返回方法。

【讨论】:

猜你喜欢
  • 2020-11-15
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-20
  • 2013-12-09
  • 2010-12-16
  • 2016-04-21
相关资源
最近更新 更多