13

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

我遇到的一个挫折是在测试响应时......

200状态很简单:

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

但是400+我被迫要么包装在 a 中try-catch,要么测试默认情况下抛出的HttpResponseException那个。RESTClient

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

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

理想情况下,我希望我的测试更像这个(如果你不使用 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
}

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

4

3 回答 3

17

@JonPeterson 想出了我认为更好的解决方案,所以我给他的答案打了勾:

client.handler.failure = client.handler.success

更多信息在这里


我(以前)找到的解决方案:

 restClient.handler.failure = { it }

哪个是简写

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

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

 restClient.handler.failure = { resp, data -> resp.setData(data); return resp }
于 2013-10-23T21:16:20.087 回答
11

正如 Tomasz 已经在评论中链接的那样,这是我对类似问题的简短回答

client.handler.failure = client.handler.success
于 2015-08-01T12:30:37.183 回答
1

一种方法是制作一个 Groovy 便捷方法,该方法包装您的 REST 调用,捕获异常并将它们转换为状态代码

于 2013-10-23T19:36:40.937 回答