如何将 groovyx.net.http.HttpResponseDecorator 转换为用户定义的类



我正在使用Spock Framework编写一个集成测试类,我的响应在groovyx.net.http.HttpResponseDecorator

我正在尝试使用以下步骤投射到我自己的类中,让我们说TestEntity

HttpResponseDecorator response = getRestClient().delete([path: "$BASE_URL"+"/96023"])

这里 Path 方法返回TestEntity,现在我想获取那个实体并写断言

TestEntity entity = (TestEntity)response.getData()

当我写这句话时,我得到了ERROR! org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object

getData()返回的类取决于返回您正在调用的 REST API 的内容类型。

添加此行以检查 Groovy 在您的情况下使用哪个类:

println response.data.getClass()

。或在 IDE 中使用调试来获取相同的信息。

例如,对于内容类型:

  • 使用类org.apache.groovy.json.internal.LazyMapapplication/json
  • 使用类groovy.util.slurpersupport.NodeChildapplication/xml
  • 使用类java.io.StringReadertext/plain

如果你正在测试后端,它使用TestEntity类作为响应(例如在 Spring 中使用@RestController@RequestMapping(,那么你在客户端中将没有TestEntity实例(Spock 测试(。

最新更新