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'], 'Hello, World'),
  10. new Response(202, ['Content-Length' => 0]),
  11. new RequestException('Error Communicating with Server', new Request('GET', 'test'))
  12. ]);
  13. $handlerStack = HandlerStack::create($mock);
  14. $client = new Client(['handler' => $handlerStack]);
  15. // The first request is intercepted with the first response.
  16. $response = $client->request('GET', '/');
  17. echo $response->getStatusCode();
  18. //> 200
  19. echo $response->getBody();
  20. //> Hello, World
  21. // The second request is intercepted with the second response.
  22. echo $client->request('GET', '/')->getStatusCode();
  23. //> 202
  24. // Reset the queue and queue up a new response
  25. $mock->reset();
  26. $mock->append(new Response(201));
  27. // As the mock was reset, the new response is the 201 CREATED,
  28. // instead of the previously queued RequestException
  29. echo $client->request('GET', '/')->getStatusCode();
  30. //> 201

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