HTTP Unit Testing (original) (raw)
Overview
Setup Instructions
Component Modules
Android
Google App Engine
HTTP Transport
JSON
Exponential Backoff
Unit Testing
Support
When writing unit tests using this HTTP framework, don’t make requests to a real server. Instead, mock the HTTP transport and inject fake HTTP requests and responses. Thepluggable HTTP transport layer of the Google HTTP Client Library for Java makes this flexible and simple to do.
Also, some useful testing utilities are included in thecom.google.api.client.testing.http package (@Beta).
The following simple example generates a basic HttpResponse:
HttpTransport transport = new MockHttpTransport();
HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
The following example shows how to override the implementation of the MockHttpTransport class:
HttpTransport transport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
response.addHeader("custom_header", "value");
response.setStatusCode(404);
response.setContentType(Json.MEDIA_TYPE);
response.setContent("{\"error\":\"not found\"}");
return response;
}
};
}
};
HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
HttpResponse response = request.execute();
For more examples, see the HttpResponseTest.java andHttpRequestTest.java files.