Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override RESTClient default "HttpResponseException" response to >399 Return Codes?

I'm using the Groovy RESTClient class to do write some (spock) Acceptance tests for Java WebServices I've been authoring.

One frustration I've had is in testing the responses...

200 Status's are easy:

when:  def result = callServiceWithValidParams()
then:  result.status == 200

But with 400+ I'm forced to either wrap in a try-catch, or test for the HttpResponseException that RESTClient throws by default.

when:
    callWithInvalidParams()
then:
    def e = thrown(Exception)
    e.message == 'Bad Request'

This is sort-of OK, if a little frustrating... but I want to do better.

Ideally, I want my tests to more resemble this (might be confusing if you don't use groovy/spock)

@Unroll
def "should return #statusCode '#status' Response"()
{
    when:
    def result = restClient.get(path: PATH, query: [param: parameter])

    then:
    result.status == statusCode

    where:
    status         | statusCode | parameter                
    'OK'           | 200        | validParam
    'Bad Request'  | 400        | invalidParam
}

In the above example, the 'Bad Request' case fails. Instead of returning a value, restClient.get() throws HttpResponseException

like image 843
Zach Lysobey Avatar asked Oct 23 '13 16:10

Zach Lysobey


2 Answers

@JonPeterson came up with what I think is a better solution, so I gave his answer the checkmark:

client.handler.failure = client.handler.success

More info here


The solution I (previously) landed on:

 restClient.handler.failure = { it }

Which is shorthand for

restClient.handler.failure = { resp -> return resp }

@JimmyLuong noted in the comments that this approach drops the data from the response, and suggested the following enhancement:

 restClient.handler.failure = { resp, data -> resp.setData(data); return resp }
like image 191
Zach Lysobey Avatar answered Nov 16 '22 01:11

Zach Lysobey


As Tomasz already linked in a comment, here is my little one-liner answer from a similar question.

client.handler.failure = client.handler.success
like image 30
Jon Peterson Avatar answered Nov 16 '22 03:11

Jon Peterson