如何在 Laravel 的测试控制器中模拟其他类函数



我正在尝试测试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 服务容器中。但是,您的控制器不会从 Laravel 服务容器中提取TheHelper实例;它使用 new 关键字手动实例化它。使用 new 关键字是核心 PHP,根本不涉及 Laravel。

您的测试显示代码中存在问题。 TheHelper是方法的依赖项,因此应传递到方法中,而不是在方法中创建。

您要么需要更新控制器方法以使用依赖注入,以便 Laravel 可以从其容器自动解析TheHelper依赖项,要么需要将 new 关键字替换为对 Laravel 容器的调用。

使用依赖注入:

public function A(Request $request, TheHelper $helper)
{
    $result = $helper->getResult($request->email);
    // rest of function...
}

从容器中手动拉取:

public function A(Request $request)
{
    $helper = app(TheHelper::class);
    $result = $helper->getResult($request->email);
    // rest of function...
}

最新更新