【问题标题】:How to use MockFor to mock client on HttpBuilder?如何使用 MockFor 在 HttpBuilder 上模拟客户端?
【发布时间】:2012-12-09 18:17:14
【问题描述】:

我想测试一些 Grails 生产代码,我在这里看到了一些示例,见下文。问题是我在 HttpBuilder 的客户端部分遇到了 MissimgMethodExceptions。这是我要测试的生产代码:

class RunkeeperActivitiesRetrieverService {
    def http = new RESTClient("http://api.runkeeper.com/")

    def getActivities() {
        http.client.clearRequestInterceptors();
        http.client.addRequestInterceptor(new HttpRequestInterceptor() {
            void process(HttpRequest httpRequest, HttpContext httpContext) {
                httpRequest.addHeader('Authorization', 'Bearer xxxxxxxxxx')
            }
        })
        //Do more with the httpBuilder
    }
}

我在这里找到了一些关于模拟 HTTPBuilder 主题的帮助:Groovy HTTPBuilder Mocking the Response 和一些关于在 groovy 文档中模拟接口的帮助:http://groovy.codehaus.org/Groovy+way+to+implement+interfaces

使用该代码我来到了这个测试代码:

def mock = new MockFor(HTTPBuilder)
def impl = [
    addRequestInterceptor : {HttpRequestInterceptor interceptor -> println "hi 4"+interceptor},
    clearRequestInterceptors : {println "hi 88"}
            ]
def client = impl as HttpClient

mock.demand.getClient {return client}
mock.use{
    service.http = new HTTPBuilder()
    println service.getActivities()
}

不幸的是,我对 Groovy 的了解太有限,无法解决抛出的异常:groovy.lang.MissingMethodException: No signature of method: $Proxy15.clearRequestInterceptors() is applicable for argument types: () values: []

我在这里错过了什么?

【问题讨论】:

    标签: grails groovy httpbuilder


    【解决方案1】:

    您正在将impl 转换为HttpClient - 它似乎没有在that interface 上定义相关方法。也许您的意思是使用AbstractHttpClient 的某个子类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      相关资源
      最近更新 更多