gpt4 book ai didi

laravel-5 - Laravel 5.6 模拟 Guzzle 响应

转载 作者:行者123 更新时间:2023-12-05 02:13:01 25 4
gpt4 key购买 nike

我正在尝试模拟来自特定 api 的 guzzle 响应。

我的 Controller 代码如下所示(为简洁起见进行了修改):

class SomeClass
{

private $guzzle;

public function __construct(\GuzzleHttp\Client $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(\GuzzleHttp\Client::class);

$mock->method('request')->willReturn([
'response' => 'somedata'
]);

$someClass = new $SomeClass($mock);

$response = $someClass->makeRequest();

$body = $response->getBody();

...
}

此时测试返回“Call to a member function getBody on null”;

如何测试 guzzle 调用的 getBody 响应?

提前致谢...

最佳答案

使用 Guzzle 进行测试的一种方法是配置 MockHandler

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

因此,您可以像这样创建一个 guzzle 客户端,而不是模拟 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 - Laravel 5.6 模拟 Guzzle 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com