Search code examples
phpunit-testingguzzlemockerypsr-7

How To Use Mockery For Mocking Nested Object Like GuzzleHttp Request


I have the following code in PHP:

$response = $this->client->request('GET', $path, $requestBody, $headers);
$isRequestSuccess = $response->getStatusCode() === "200";

if ($isRequestSuccess) {
    return $response->getBody()->getContents();
}

It seems like I was successful in creating a mock for the request:

$mockResponse = \Mockery::mock('GuzzleHttp\Psr7\Response');

$clientMock
    ->shouldReceive('request')
    ->once()
    ->withAnyArgs()
    ->andReturn($mockResponse);

$clientMock->shouldReceive('getStatusCode')->andReturn(200);

But, how should I use Mockery to mock getStatusCode?

It should return a Psr7\Response object of GuzzleHttp.

I know that the $clientMock return value should be assigned to a parameter, but how should I mock the

$response->getStatusCode();

and

$response->getBody()->getContents()

If I'm going to mock the getStatusCode and return 200, I get the following error:

Method Mockery_4_GuzzleHttp_Psr7_Response::getStatusCode() does not exist on this mock object

Solution

  • It is not a $request, it is a $response, you better name it so. It Is very confusing that $request variable contains a response object.

    Anyway,

    Mockery::mock(ResponseInterface::class)->shouldReceive('getStatusCode')->andReturn(200);
    

    Looking at it deeper, you probably dont have to care, that response Is mocked and useless to test, you would be testing if you set up the mock right, rather then testing your code.