Testing Guzzle Clients

Guzzle provides several tools that will enable you to easily mock the HTTPlayer without needing to send requests over the internet.

  • Mock handler
  • History middleware
  • Node.js web server for integration testing

Mock Handler

When testing HTTP clients, you often need to simulate specific scenarios likereturning a successful response, returning an error, or returning specificresponses in a certain order. Because unit tests need to be predictable, easyto 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 witha 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.  
  8. // Create a mock and queue two responses.
  9. $mock = new MockHandler([
  10. new Response(200, ['X-Foo' => 'Bar']),
  11. new Response(202, ['Content-Length' => 0]),
  12. new RequestException("Error Communicating with Server", new Request('GET', 'test'))
  13. ]);
  14.  
  15. $handler = HandlerStack::create($mock);
  16. $client = new Client(['handler' => $handler]);
  17.  
  18. // The first request is intercepted with the first response.
  19. echo $client->request('GET', '/')->getStatusCode();
  20. //> 200
  21. // The second request is intercepted with the second response.
  22. echo $client->request('GET', '/')->getStatusCode();
  23. //> 202

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

History Middleware

When using things like the Mock handler, you often need to know if therequests you expected to send were sent exactly as you intended. While the mockhandler responds with mocked responses, the history middleware maintains ahistory of the requests that were sent by a client.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\HandlerStack;
  3. use GuzzleHttp\Middleware;
  4.  
  5. $container = [];
  6. $history = Middleware::history($container);
  7.  
  8. $stack = HandlerStack::create();
  9. // Add the history middleware to the handler stack.
  10. $stack->push($history);
  11.  
  12. $client = new Client(['handler' => $stack]);
  13.  
  14. $client->request('GET', 'http://httpbin.org/get');
  15. $client->request('HEAD', 'http://httpbin.org/get');
  16.  
  17. // Count the number of transactions
  18. echo count($container);
  19. //> 2
  20.  
  21. // Iterate over the requests and responses
  22. foreach ($container as $transaction) {
  23. echo $transaction['request']->getMethod();
  24. //> GET, HEAD
  25. if ($transaction['response']) {
  26. echo $transaction['response']->getStatusCode();
  27. //> 200, 200
  28. } elseif ($transaction['error']) {
  29. echo $transaction['error'];
  30. //> exception
  31. }
  32. var_dump($transaction['options']);
  33. //> dumps the request options of the sent request.
  34. }

Test Web Server

Using mock responses is almost always enough when testing a web service client.When implementing custom HTTP handlers, you'llneed to send actual HTTP requests in order to sufficiently test the handler.However, a best practice is to contact a local web server rather than a serverover the internet.

  • Tests are more reliable
  • Tests do not require a network connection
  • Tests have no external dependencies

Using the test server

Warning

The following functionality is provided to help developers of Guzzledevelop HTTP handlers. There is no promise of backwards compatibilitywhen it comes to the node.js test server or the GuzzleHttp\Tests\Serverclass. If you are using the test server or Server class outside ofguzzlehttp/guzzle, then you will need to configure autoloading andensure the web server is started manually.

Hint

You almost never need to use this test web server. You should only everconsider using it when developing HTTP handlers. The test web serveris not necessary for mocking requests. For that, please use theMock handler and history middleware.

Guzzle ships with a node.js test server that receives requests and returnsresponses from a queue. The test server exposes a simple API that is used toenqueue responses and inspect the requests that it has received.

Any operation on the Server object will ensure thatthe server is running and wait until it is able to receive requests beforereturning.

GuzzleHttp\Tests\Server provides a static interface to the test server. Youcan queue an HTTP response or an array of responses by callingServer::enqueue(). This method accepts an array ofPsr\Http\Message\ResponseInterface and Exception objects.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\Psr7\Response;
  3. use GuzzleHttp\Tests\Server;
  4.  
  5. // Start the server and queue a response
  6. Server::enqueue([
  7. new Response(200, ['Content-Length' => 0])
  8. ]);
  9.  
  10. $client = new Client(['base_uri' => Server::$url]);
  11. echo $client->request('GET', '/foo')->getStatusCode();
  12. // 200

When a response is queued on the test server, the test server will remove anypreviously queued responses. As the server receives requests, queued responsesare dequeued and returned to the request. When the queue is empty, the serverwill return a 500 response.

You can inspect the requests that the server has retrieved by callingServer::received().

  1. foreach (Server::received() as $response) {
  2. echo $response->getStatusCode();
  3. }

You can clear the list of received requests from the web server using theServer::flush() method.

  1. Server::flush();
  2. echo count(Server::received());
  3. // 0