laravel PHPUnit 和来自 Guzzle 的模拟请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49013014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHPUnit and mock request from Guzzle
提问by themazz
I have a class with the following function :
我有一个具有以下功能的类:
public function get(string $uri) : stdClass
{
$this->client = new Client;
$response = $this->client->request(
'GET',
$uri,
$this->headers
);
return json_decode($response->getBody());
}
How can I mock the request method from PHPUnit? I tried different ways but it always tries to connect to the uri specified.
如何从 PHPUnit 模拟请求方法?我尝试了不同的方法,但它总是尝试连接到指定的 uri。
I tried with :
我试过:
$clientMock = $this->getMockBuilder('GuzzleHttp\Client')
->setMethods('request')
->getMock();
$clientMock->expects($this->once())
->method('request')
->willReturn('{}');
But this didn't work. What can I do? I just need to mock the response to be empty.
但这没有用。我能做什么?我只需要模拟响应为空。
Thanks
谢谢
PD : Client comes from (use GuzzleHttp\Client)
PD :客户端来自(使用 GuzzleHttp\Client)
回答by themazz
I think as suggested is better to use http://docs.guzzlephp.org/en/stable/testing.html#mock-handler
我认为建议最好使用http://docs.guzzlephp.org/en/stable/testing.html#mock-handler
as it looks like the most elegant way to do it properly.
因为它看起来是最优雅的正确方式。
Thank you all
谢谢你们
回答by duncan
The mocked Response doesn't need to be anything in particular, your code just expects it to be an object with a getBody
method. So you can just use a stdClass
, with a getBody
method which returns some json_encoded
object. Something like:
模拟的 Response 不需要是任何特别的东西,您的代码只希望它是一个带有getBody
方法的对象。所以你可以只使用stdClass
, 和一个getBody
返回一些json_encoded
对象的方法。就像是:
$jsonObject = json_encode(['foo']);
$uri = '/foo/bar/';
$mockResponse = $this->getMockBuilder(\stdClass::class)->getMock();
mockResponse->method('getBody')->willReturn($jsonObject);
$clientMock = $this->getMockBuilder('GuzzleHttp\Client')->getMock();
$clientMock->expects($this->once())
->method('request')
->with(
'GET',
$uri,
$this->anything()
)
->willReturn($mockResponse);
$result = $yourClass->get($uri);
$expected = json_decode($jsonObject);
$this->assertSame($expected, $result);