【问题标题】:How do I mock guzzle request我如何模拟 guzzle 请求
【发布时间】:2020-04-22 06:22:56
【问题描述】:

如何模拟第三方 api 调用。这是从控制器发生的。我在控制器中有这行代码。

public function store(){
  $response =    $request->post('http://thirdpaty.app/rmis/api/ebp/requests', [
                  "headers" => [
                      'Content-Type' => 'application/json',
                   ],
                "json" => [
                  "data"=>1
                   ]
            ]);
                $data = json_decode($response->getBody()->getContents());
                $token = $data->token;

         // Saving that token to database

}

从我正在做的测试来看

$response = $this->post('/to-store-method');

如何模拟 api 请求。这样在测试中我就不必调用第三个 api 请求了。

我现在正在做

if(app()->get('env') == 'testing'){
     $token = 123;
}else{
     //Api call here
  }

有没有更好的选择来做这个测试

【问题讨论】:

    标签: laravel testing mocking phpunit guzzle


    【解决方案1】:

    您需要某种方式将模拟处理程序注入控制器正在使用的 Guzzle 客户端。传统上,您要么通过构造函数传递 Guzzle 客户端来利用依赖注入,要么通过代码中的一些引用服务来利用依赖注入,您可以在幕后模拟(使用 Mockery)。

    之后,查看 Guzzle 文档,了解如何在 HTTP 客户端中模拟请求:

    http://docs.guzzlephp.org/en/stable/testing.html

    您将使用 MockHandler 通过构建一堆虚假请求和响应来执行类似于以下代码的操作。

    // Create a mock and queue two responses.
    $mock = new MockHandler([
        new Response(200, ['X-Foo' => 'Bar'], 'Hello, World'),
        new Response(202, ['Content-Length' => 0]),
        new RequestException('Error Communicating with Server', new Request('GET', 'test'))
    ]);
    
    $handlerStack = HandlerStack::create($mock);
    $client = new Client(['handler' => $handlerStack]);
    
    // The first request is intercepted with the first response.
    $response = $client->request('GET', '/');
    

    【讨论】:

    • 你知道注入的方法吗?
    【解决方案2】:

    实际上,模拟网络库是一种不好的做法。我建议的是通过 httpService 包装网络请求并模拟 httpService 以返回所需的响应。

    public function store(){
      $response =   httpService.postData();
                    $data = json_decode($response->getBody()->getContents());
                    $token = $data->token;
    
             // Saving that token to database
    
    }
    

    因此,您将从 httpService.postData 函数获得响应作为返回,并且您可以模拟 postData 而不是网络库。

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 2018-08-07
      • 2017-10-05
      • 1970-01-01
      • 2015-10-30
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多