Testing Guzzle Clients
- Mock handler
- Node.js web server for integration testing
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.
When no more responses are in the queue and a request is sent, an is thrown.
When using things like the Mock
handler, you often need to know if the requests you expected to send were sent exactly as you intended. While the mock handler responds with mocked responses, the history middleware maintains a history of the requests that were sent by a client.
- Tests are more reliable
- Tests have no external dependencies
Warning
The following functionality is provided to help developers of Guzzle develop HTTP handlers. There is no promise of backwards compatibility when it comes to the node.js test server or the GuzzleHttp\Tests\Server
class. If you are using the test server or class outside of guzzlehttp/guzzle, then you will need to configure autoloading and ensure the web server is started manually.
Hint
You almost never need to use this test web server. You should only ever consider using it when developing HTTP handlers. The test web server is not necessary for mocking requests. For that, please use the Mock handler and history middleware.
Any operation on the Server
object will ensure that the server is running and wait until it is able to receive requests before returning.
GuzzleHttp\Tests\Server
provides a static interface to the test server. You can queue an HTTP response or an array of responses by calling . This method accepts an array of Psr\Http\Message\ResponseInterface
and Exception
objects.
When a response is queued on the test server, the test server will remove any previously queued responses. As the server receives requests, queued responses are dequeued and returned to the request. When the queue is empty, the server will return a 500 response.
You can inspect the requests that the server has retrieved by calling .