我正在编写一个集成测试,只想模拟类中的单个方法,以防止它与“外部世界”接触
我的类有 2 个公共方法,我想用回调替换方法“dispatchMessage”,它只是返回我的输入值而不做任何进一步的事情。
我目前的尝试是这样的:
/* @var ChargeReportServiceInterface $mock */
$reportService = $this
->getMockBuilder(ChargeReportServiceInterface::class)
->enableOriginalConstructor()
->onlyMethods(['dispatchMessage'])
->getMock();
$reportService
->method('dispatchMessage')
->willReturnCallback(
function ($message) {
return $message;
}
);
return $reportService;
这会导致消息:
PHP Fatal error: Class MockObject_ChargeReportServiceInterface_fde2b860 contains 1 abstract method and must therefore be declared abstract or implement the remaining methods
仅模拟“dispatchMessage”方法并保留其余部分的正确方法是什么?
以下代码有效:
/* @var ChargeReportService $mock */
$reportService = $this
->getMockBuilder(ChargeReportService::class)
->disableOriginalConstructor()
->onlyMethods(['dispatchMessage'])
->getMock();
$reportService
->method('dispatchMessage')
->willReturnCallback(
function ($message) {
return $message;
}
);
return $reportService;
所以我用类本身替换了接口。然后我禁用了构造函数,因为幸运的是我不需要任何注入的对象。 等等瞧!我可以访问 $message 的返回值,而该类的其他公共方法按预期工作。