我想在API返回404时为GET请求编写测试。
我的测试:
def "Should return 404 - object deleted before"() {
setup:
def advertisementEndpoint = new RESTClient( 'http://localhost:8080/' )
when:
def resp = advertisementEndpoint.get(
path: 'api/advertisement/1',
contentType: groovyx.net.http.ContentType.JSON
)
then:
resp.status == 404
}
我的错误:
14:24:59.294 [main] DEBUG o.a.h.impl.client.DefaultHttpClient - 连接可以无限期地保持活动14:24:59.305 [主要] DEBUG groovyx.net.http.RESTClient - 响应代码:404;找到处理程序 org.codehaus.groovy.runtime.MethodClosure@312aa7c 14:24:59.306 [主要] DEBUG groovyx.net.http.RESTClient - 解析响应为: application / json 14:24:59.443 [main] DEBUG org.apache.http.wire - << “ba [\ r] [\ n]”14:24:59.444 [main] DEBUG org.apache.http.wire - << “{” 时间戳 “:1436358299234,” 状态 “:404,” 错误 “:” 不 找到 “ ”异常“: ”com.pgssoft.exparo.web.ResourceNotFoundException“, ”消息“:” 无 消息可用“,”路径“:”/ api / advertise / 1“}”14:24:59.445 [主要] DEBUG org.apache.http.wire - << “[\ r] [\ n]”14:24:59.445 [主要] DEBUG org.apache.http.wire - << “0 [\ r] [\ n]”14:24:59.446 [主要] DEBUG org.apache.http.wire - << “[\ r] [\ n]”14:24:59.446 [主要] DEBUG o.a.h.i.c.BasicClientConnectionManager - 释放连接 org.apache.http.impl.conn.ManagedClientConnectionImpl@2ab4bc72 14:24:59.446 [main] DEBUG o.a.h.i.c.BasicClientConnectionManager - 连接可以无限期地保持活动14:24:59.449 [main] DEBUG groovyx.net.http.RESTClient - 解析数据到:class的实例 groovy.json.internal.LazyMap
groovyx.net.http.HttpResponseException:找不到 groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:263) 在groovy.lang.Closure.call(Closure.java:423)at groovyx.net.http.HTTPBuilder $ 1.handleResponse(HTTPBuilder.java:503) 在 org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:218) 在 org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:160) 在groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:515)at groovyx.net.http.RESTClient.get(RESTClient.java:119)at AdvertisementTest.Should返回404 - 对象删除 之前(AdvertisementTest.groovy:79)
答案 0 :(得分:1)
您需要基础HTTPBuilder
的失败处理程序。来自HTTPBuilder
javadoc:
您还可以设置为任何状态代码调用的默认响应处理程序 399与特定处理程序不匹配。在请求关闭之外设置值意味着它将适用于所有将来的请求 使用此HTTPBuilder实例:
http.handler.failure = { resp -> println "Unexpected failure: ${resp.statusLine}" }
因此:
@Grapes(
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
)
import groovyx.net.*
import groovyx.net.http.*
def restClient = new RESTClient('http://localhost/wrong')
restClient.handler.failure = { resp -> resp.status }
def response = restClient.get([:])
assert response == 404