Test Web Server
Using mock responses is almost always enough when testing a web service client. When implementing custom HTTP handlers, you’ll need 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 server over the internet.
- Tests are more reliable
- Tests do not require a network connection
- Tests have no external dependencies
Using the test server
警告
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 Server
class outside of guzzlehttp/guzzle, then you will need to configure autoloading and ensure the web server is started manually.
提示
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.
Guzzle ships with a node.js test server that receives requests and returns responses from a queue. The test server exposes a simple API that is used to enqueue responses and inspect the requests that it has received.
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 Server::enqueue()
. This method accepts an array of Psr\Http\Message\ResponseInterface
and Exception
objects.
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Tests\Server;
// Start the server and queue a response
Server::enqueue([
new Response(200, ['Content-Length' => 0])
]);
$client = new Client(['base_uri' => Server::$url]);
echo $client->request('GET', '/foo')->getStatusCode();
// 200
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 Server::received()
.
foreach (Server::received() as $response) {
echo $response->getStatusCode();
}
You can clear the list of received requests from the web server using the Server::flush()
method.
Server::flush();
echo count(Server::received());
// 0