来自Guzzle的PHPUnit和模拟请求

问题描述 投票:3回答:2

我有一个具有以下功能的类:

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)

php laravel mocking phpunit guzzle
2个回答
5
投票

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

因为它看起来是最优雅的方式来正确地做到这一点。

谢谢你们


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);
© www.soinside.com 2019 - 2024. All rights reserved.