【发布时间】:2019-11-27 13:30:23
【问题描述】:
我正在尝试在 Laravel 中测试一个控制器,它使用另一个类作为助手,它调用 API 并返回结果。
为了避免外部 API 调用,我需要模拟这个助手。
我尝试在控制器中模拟类并运行测试,但没有得到我在模拟类中的预期。
这是我的控制器方法:
public function A(Request $request){
$helper = new TheHelper();
$result = $helper->getResult($request->email);
if($result){
return response()->json([
'success' => true,
'message' => "result found",
], 200);
}else{
return response()->json([
'success' => false,
'message' => "no result",
], 500);
}
}
我的辅助方法只是调用一个 API 并返回结果。
class TheHelper
{
public function getResult($email){
// some api calls
return $result;
}
}
这是我的测试:
public function testExample()
{
$helperMock = Mockery::mock(TheHelper::class);
// Set expectations
$helperMock ->shouldReceive('getResult')
->once()
->with('testemail@test.com')
->andReturn([
'id' => '100'
]);
$this->app->instance(TheHelper::class, $helperMock);
$this->json(
'POST',
'/api/test_method',
['email' => 'testemail@test.com'])
->assertStatus(200);
}
我的模拟函数从未调用过。它只检查 TheHelper 方法中的真实 API
【问题讨论】:
标签: laravel mocking integration-testing