我可以覆盖RESTClient默认的"HttpResponseException"响应> 399返回代码吗?

Zac*_*bey 13 testing groovy rest-client spock

我正在使用Groovy RESTClient类为Java WebServices写一些(spock)验收测试我一直在创作.

我遇到的一个挫折就是测试答案......

200 状态很简单:

when:  def result = callServiceWithValidParams()
then:  result.status == 200
Run Code Online (Sandbox Code Playgroud)

但是400+我被迫要么包装,要么默认try-catch测试HttpResponseException那个RESTClient抛出.

when:
    callWithInvalidParams()
then:
    def e = thrown(Exception)
    e.message == 'Bad Request'
Run Code Online (Sandbox Code Playgroud)

这有点好,如果有点令人沮丧......但我想做得更好.

理想情况下,我希望我的测试更像这样(如果你不使用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
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,"错误请求"案例失败.restClient.get()抛出而不是返回值HttpResponseException

Zac*_*bey 17

选择@JonPeterson,我认为这是一个更好的解决方案,所以我给了他的答案:

client.handler.failure = client.handler.success
Run Code Online (Sandbox Code Playgroud)

更多信息在这里


我(之前)解决的解决方案:

 restClient.handler.failure = { it }
Run Code Online (Sandbox Code Playgroud)

这是简写

restClient.handler.failure = { resp -> return resp }
Run Code Online (Sandbox Code Playgroud)

@JimmyLuong在评论中指出,这种方法会从响应中删除数据,并建议以下增强:

 restClient.handler.failure = { resp, data -> resp.setData(data); return resp }
Run Code Online (Sandbox Code Playgroud)

  • 除了从响应中删除数据之外,使用此解决方案对我来说效果很好.要获取数据,我必须执行以下操作:restClient.handler.failure = {resp,data - > resp.setData(data); 返回resp} (5认同)

Jon*_*son 11

正如Tomasz在评论中已经联系起来的,这是我在类似问题上的一点回答.

client.handler.failure = client.handler.success
Run Code Online (Sandbox Code Playgroud)