PHPUnit and mock request from Guzzle

themazz picture themazz · Feb 27, 2018 · Viewed 9.9k times · Source

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.

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)

Answer

themazz picture themazz · Feb 27, 2018

I think as suggested is better to use 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