Mock Handler

When testing HTTP clients, you often need to simulate specific scenarios like returning a successful response, returning an error, or returning specific responses in a certain order. Because unit tests need to be predictable, easy to bootstrap, and fast, hitting an actual remote API is a test smell.

Guzzle provides a mock handler that can be used to fulfill HTTP requests with a response or exception by shifting return values off of a queue.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\Handler\MockHandler;
  3. use GuzzleHttp\HandlerStack;
  4. use GuzzleHttp\Psr7\Response;
  5. use GuzzleHttp\Psr7\Request;
  6. use GuzzleHttp\Exception\RequestException;
  7. // Create a mock and queue two responses.
  8. $mock = new MockHandler([
  9. new Response(200, ['X-Foo' => 'Bar']),
  10. new Response(202, ['Content-Length' => 0]),
  11. new RequestException("Error Communicating with Server", new Request('GET', 'test'))
  12. ]);
  13. $handler = HandlerStack::create($mock);
  14. $client = new Client(['handler' => $handler]);
  15. // The first request is intercepted with the first response.
  16. echo $client->request('GET', '/')->getStatusCode();
  17. //> 200
  18. // The second request is intercepted with the second response.
  19. echo $client->request('GET', '/')->getStatusCode();
  20. //> 202

When no more responses are in the queue and a request is sent, an OutOfBoundsException is thrown.