Laravel 5.6模拟Guzzle响应
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel 5.6模拟Guzzle响应相关的知识,希望对你有一定的参考价值。
我试图嘲笑特定api的guzzle响应。
我的控制器代码看起来像这样(为简洁起见):
class SomeClass
{
private $guzzle;
public function __construct(GuzzleHttpClient $guzzle) {
$this->guzzle = new $guzzle();
}
public function makeRequest(){
$client = $this->guzzle;
$url = 'http//somerurl';
$options = [];
$response = $client->request('POST', $url, $options);
return $response;
}
}
测试看起来像这样(再次编辑)......
public function someTest(){
$mock = $this->createMock(GuzzleHttpClient::class);
$mock->method('request')->willReturn([
'response' => 'somedata'
]);
$someClass = new $SomeClass($mock);
$response = $someClass->makeRequest();
$body = $response->getBody();
...
}
此时测试返回“调用成员函数getBody on null”;
如何测试一个guzzle call的getBody响应?
先感谢您...
答案
使用Guzzle进行测试的一种方法是配置MockHandler
http://docs.guzzlephp.org/en/stable/testing.html
因此,不要嘲笑guzzle客户端,而是创建一个这样的:
public function someTest() {
$mock = new MockHandler([
new Response(200, [], 'The body!'),
// Add more responses for each response you need
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$someClass = new SomeClass($client);
$response = $someClass->makeRequest();
$body = $response->getBody();
$this->assertSame('The body!', $body);
}
以上是关于Laravel 5.6模拟Guzzle响应的主要内容,如果未能解决你的问题,请参考以下文章
减少对外部 API 的身份验证调用(Laravel 5.6)
利用Guzzle实现另一种PHP异步发送邮件(laravel5.4)