【问题标题】:Can I override RESTClient default "HttpResponseException" response to >399 Return Codes?我可以覆盖 RESTClient 对 >399 返回代码的默认“HttpResponseException”响应吗?
【发布时间】:2013-10-23 16:04:22
【问题描述】:

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

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

200 状态很简单:

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

但是对于400+,我不得不要么包装在try-catch 中,要么测试RESTClient 默认抛出的HttpResponseException

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

【问题讨论】:

  • 很难理解你面临的障碍。你能发布更多信息吗?参数是什么类型?当您尝试使用 where 块来定义参数时会发生什么? callService() 是什么样子的?
  • @AlexBlakemore 感谢您的回复。最后的示例只是为了说明我的原始请求如何帮助我。我现在看到它有点令人困惑,因为我实际上并没有显示 RESTClient。将callService(params) 视为客户端的包装器,其中params 值是要发送到服务的queryString 参数的映射。不过,所有这些都不是很重要。要点是 RESTService 为 200 个响应返回一个 result,但对 400、401 等抛出一个错误......所以我无法在我的 then: 块中以标准方式测试响应
  • 刚刚编辑了示例以希望使其更简单/清晰。
  • 那为什么不做一个方便的方法来包装你的 REST 调用来捕获异常并将它们转换为状态码呢?
  • 我想我可以这样做,但它会变得有点草率。一方面,我必须创建一种方法来将错误名称(如“错误请求”、“未授权”...)映射到 HttpResponseException 中不存在的相应代码(400、401...) .归根结底,这种方法是可以的(如果你想要一些互联网点,也许值得一个答案),但我只是希望可能有一种更优雅的方法来实现这一点。

标签: testing groovy spock rest-client


【解决方案1】:

@JonPeterson 提出了我认为更好的解决方案,所以我给his answer 打勾:

client.handler.failure = client.handler.success

More info here


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

 restClient.handler.failure = { it }

什么是简写

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

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

 restClient.handler.failure = { resp, data -> resp.setData(data); return resp }

【讨论】:

  • 对我来说使用这个解决方案效果很好,除了从响应中删除的数据。要获取数据,我必须执行以下操作:restClient.handler.failure = { resp, data -> resp.setData(data);返回响应}
  • @TomaszKalkosiński 建议的方法更简单,而且效果很好
【解决方案2】:

正如 Tomasz 已在评论中链接的那样,这是来自类似问题的我的小单线 answer

client.handler.failure = client.handler.success

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2016-10-21
      • 1970-01-01
      • 2016-12-12
      • 2011-05-01
      • 2013-07-22
      • 2017-02-24
      • 2019-08-29
      • 2020-08-10
      • 2014-01-28
      相关资源
      最近更新 更多