Class HttpClientTestRule

java.lang.Object
org.nuxeo.http.test.HttpClientTestRule
All Implemented Interfaces:
org.junit.rules.TestRule

public class HttpClientTestRule extends Object implements org.junit.rules.TestRule
This is an HttpClient wrapped as a JUnit TestRule to perform needed cleanup on teardown.

In a unit test with an embedded Nuxeo, the client can be instantiated like below:

 @Inject
 protected ServletContainerFeature servletContainerFeature;
 
 @Rule
 public final HttpClientTestRule httpClient = HttpClientTestRule.defaultJsonClient(
         () -> servletContainerFeature.getHttpUrl());
 
The client is now ready to execute requests on http://localhost:PORT. The default JSON client has the following configuration:
  • uses Administrator:Administrator basic auth
  • sends the Accept header with application/json value
  • sends the Content-Type header with application/json value
The most interesting way to use the client is with handler and executeAnd* APIs, for example:
 httpClient.buildGetRequest("/api/v1/me").executeAndConsume(new JsonNodeHandler(), node -> {
     assertEquals("user", node.get("entity-type").asText());
     assertEquals("Administrator", node.get("id").asText());
 });
 
In this example, we execute a GET request to /api/v1/me endpoint, and then we consume the HTTP response with the JsonNodeHandler handler which asserts that the HTTP response status code has the value 200, asserts that the header Content-Type has the application/json value, deserializes the response entity to a JsonNode, and gives it to the lambda passed as second parameter.

When an error or an assertion failure occurs, in the handler or custom assertion, the client will automatically log the HTTP request and response related to the failure.

Since:
2023.13
See Also: