Integrationtests with Groovy’s HTTP Builder

The HTTP Builder for Groovy simplyfies the creation and handling of HTTP requests. It is a wrapper around the Apache HttpClient adding a closure based API which increases readablitity and brevity.

I started to use the HTTP Builder in integration tests. Let’s take a look:

void test_myPage_shouldRedirectToLogin() {
  def baseURI = "http://servername"
  def httpBuilder = new HTTPBuilder(baseURI)
  // Make sure that HttpClient doesn't perform a redirect
  def dontHandleRedirectStrategy = [
    getRedirect : { request, response, context -> null},
    isRedirected : { request, response, context -> false}
  httpBuilder.client.setRedirectStrategy(dontHandleRedirectStrategy as RedirectStrategy)

  // Execute a GET request and expect a redirect
  httpBuilder.request(Method.GET, ContentType.TEXT) {
    req ->
      uri.path = '/webapp/de/de/myPage'
      response.success = { response, reader ->
        assertThat response.statusLine.statusCode, is(302)
        assertThat response.headers['Location'].value, startsWith("${baseURI}/webapp/login")
      response.failure = { response, reader ->
        fail("Expected redirect but received ${response.statusLine} \n ${reader}")

There are different overloaded versions of the request method. In the example I just use the variant which requires the HTTP Method and the expected content type. In the following configuration closure the request uri path is defined as well as the success and the failure closure. The failure closure will be executed when the status code is greater or equal than 400. Otherwise success will run. Each closure will be called with a HttpResponse object and a reader representing the response body.

Normally the Apache HttpClient will handle redirects transparently, but for this test I wanted to check if the redirect was correctly sent. So I created a new implementation of the RedirectStrategy interface using Groovy’s as operator.

HTTP Builder uses the Content Type to apply response parsing. When application/json is given, then the HTTP Builder will use the JsonSlurper to create a Map from the JSON content. For text/html the HTTP Builder provides a reader (as seen in our example).

In summary HTTP Builder is a convenient and easy to use HTTP framework. The resulting code is much more readable than when the Apache HttpClient is directly used.