我如何模拟枪口要求

问题描述 投票:0回答:1

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

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个回答
0
投票

您需要某种方式将模拟处理程序注入到控制器正在使用的Guzzle Client中。传统上,您要么通过构造函数传递Guzzle Client,要么通过可以在后台模拟(使用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', '/');
© www.soinside.com 2019 - 2024. All rights reserved.