Mockery 的 andReturn() 执行方法而不是模拟 return 值

Mockery's andReturn() executing method instead of mocking return value

我正在尝试测试以下方法:

/* ConfigurationService.php*/    

public function checkConfigs()
{
    $configurations = $this->getConfigurations();
    return $configurations['configExample'] === '1';
}

考虑到 getConfigurations() 方法调用此文件之外的其他方法,在 ConfigurationRepository.php 内,我试图仅模拟它的 return 并执行我想测试的方法( 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();

问题是,方法 getConfigurations() 执行的不是 return 模拟结果 (['configExample' => '1']),由于其中的其他方法调用而失败,return错误:

Mockery\Exception\BadMethodCallException: Received Mockery_1_App_Repositories_API_ConfigurationRepository::methodInsideGetConfigurations(), but no expectations were specified

总而言之,andReturn() 不起作用。有什么想法吗?

刚刚找到解决方案...

$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

在这些情况下,建议直接模拟方法 return,因此:

  • 我在模拟通话中添加了 makePartial()
  • 收到服务模拟本身内部的模拟结果

然后 andReturn() 方法按预期工作。