我正在尝试测试以下方法:
/* ConfigurationService.php*/
public function checkConfigs()
{
$configurations = $this->getConfigurations();
return $configurations['configExample'] === '1';
}
考虑到getConfigurations()
方法在文件ConfigurationRepository.php
中调用此文件之外的其他方法,我试图仅模拟其返回值并执行我想测试的方法(checkConfigs()
) :(省略了一些代码)
/* ConfigurationServiceTest.php */
$configurationRepoMock = \Mockery::mock(ConfigurationRepository::class);
$configurationRepoMock
->shouldReceive('getConfigurations')
->once()
->andReturn(['configExample' => '1']);
$configurationServiceMock = \Mockery::mock(ConfigurationService::class);
$this->app->instance('App\Services\ConfigurationService', $configurationServiceMock);
$configurationServiceInstance = new ConfigurationService($configurationRepoMock);
$response = $configService->checkConfigs();
问题是,执行方法['configExample' => '1']
而不是返回模拟结果(getConfigurations()
),由于其中的其他方法调用而失败,返回错误:
Mockery \ Exception \ BadMethodCallException:收到Mockery_1_App_Repositories_API_ConfigurationRepository :: methodInsideGetConfigurations(),但未指定期望
总结,andReturn()
无法正常工作。有什么想法吗?
答案 0 :(得分:0)
刚刚找到了解决方案...
$configurationServiceMock = Mockery::mock(ConfigurationService::class)->makePartial();
$configurationServiceMock
->shouldReceive('getConfigurations')
->andReturn(['configExample' => '1']);
$response = $configurationServiceMock->checkConfigs();
根据文档:http://docs.mockery.io/en/latest/cookbook/big_parent_class.html
在这些情况下,建议直接模拟方法返回,因此:
makePartial()
然后andReturn()
方法按预期工作。