0

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
Franz Noel
  • 1,820
  • 2
  • 23
  • 50

1 Answers1

1

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.

slepic
  • 641
  • 4
  • 11
  • your example works only for the `getStatusCode` method, but not necessarily for `$response->getBody()->getContents()`. I'm not mocking the response for the entire function. I would like to mock the method it calls inside it because it is part of validating the entire code nestedly. Also adding the error. – Franz Noel Jun 16 '20 at 06:03
  • I think it's my bad. I just made a mistake in `$mockResponse`. I didn't add `makePartial` call. – Franz Noel Jun 16 '20 at 06:17
  • Ah sry, you have to mock the StreamInterface and have its getContents method return the expected string, then configure the response mock's getBody method to return the mocked stream. – slepic Jun 16 '20 at 10:27