我有一个具有以下功能的课程:
public function get(string $uri) : stdClass
{
$this->client = new Client;
$response = $this->client->request(
'GET',
$uri,
$this->headers
);
return json_decode($response->getBody());
}
如何从PHPUnit模拟请求方法?我尝试了不同的方法,但它总是尝试连接到指定的uri。
我尝试过:
$clientMock = $this->getMockBuilder('GuzzleHttp\Client')
->setMethods('request')
->getMock();
$clientMock->expects($this->once())
->method('request')
->willReturn('{}');
但是这没用。我能做什么?我只需要将响应模拟为空。
由于
PD:客户端来自(使用GuzzleHttp \ Client)
答案 0 :(得分:5)
答案 1 :(得分:0)
模拟的响应不需要特别重要,您的代码只希望它是一个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);