来自Guzzle的PHPUnit和模拟请求

时间:2018-02-27 16:05:08

标签: php laravel mocking phpunit guzzle

我有一个具有以下功能的课程:

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)

2 个答案:

答案 0 :(得分:5)

我认为最好使用http://docs.guzzlephp.org/en/stable/testing.html#mock-handler

因为它看起来是最恰当的方式。

谢谢大家

答案 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);