Groovy HttpBuilder - Get Body Of Failed Response

后端 未结 3 858
后悔当初
后悔当初 2021-02-05 16:52

I am trying to use the Groovy HTTPBuilder to write an integration test that will verify a correct error message is returned in the body along with an HTTP 409 status message. Ho

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 17:16

    I also struggled with this when I started using HttpBuilder. The solution I came up with was to define the HTTPBuilder success and failure closures to return consistent values like this:

    HTTPBuilder http = new HTTPBuilder()
    http.handler.failure = { resp, reader ->
        [response:resp, reader:reader]
    }
    http.handler.success = { resp, reader ->
        [response:resp, reader:reader]
    }
    

    Thusly defined, your HTTPBuilder instance will consistently return a map containing a response object (an instance of HttpResponseDecorator) and a reader object. Your request would then look like this:

    def map = http.request(ENV_URL, Method.POST, ContentType.TEXT) {
        uri.path = "/curate/${id}/submit"
        contentType = ContentType.JSON
    }
    
    def response = map['response']
    def reader = map['reader']
    
    assert response.status == 409
    

    The reader will be some kind of object that'll give you access to the response body, the type of which you can determine by calling the getClass() method:

    println "reader type: ${reader.getClass()}"
    

    The reader object's type will be determined by the Content-Type header in the response. You can tell the server specifically what you'd like returned by adding an "Accept" header to the request.

提交回复
热议问题