【问题标题】:Spock test - RESTClient: HttpResponseException: Not FoundSpock 测试 - RESTClient:HttpResponseException:未找到
【发布时间】:2015-07-08 12:37:29
【问题描述】:

我想在 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] 调试 o.a.h.impl.client.DefaultHttpClient - 连接可以无限期地保持活动状态 14:24:59.305 [main] DEBUG groovyx.net.http.RESTClient - 响应代码:404;找到处理程序: org.codehaus.groovy.runtime.MethodClosure@312aa7c 14:24:59.306 [主要] 调试 groovyx.net.http.RESTClient - 将响应解析为: 应用程序/json 14:24:59.443 [main] 调试 org.apache.http.wire -

groovyx.net.http.HttpResponseException: 未在 groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:263) 在 groovy.lang.Closure.call(Closure.java:423) 在 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) 在 groovyx.net.http.RESTClient.get(RESTClient.java:119) 在 广告测试。应该返回 404 - 对象删除 之前(AdvertisementTest.groovy:79)

【问题讨论】:

    标签: spring groovy spring-boot spock httpbuilder


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2021-09-24
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多