Groovy HTTPBuilder模拟客户端 [英] Groovy HTTPBuilder Mocking the Client

查看:84
本文介绍了Groovy HTTPBuilder模拟客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与这个问题密切相关。不同的是,我想按照推荐的方式来嘲笑客户。因此,我定义了以下HTTPBuilder:

  protected readUrl(){
def http = new HTTPBuilder(http ://example.com)
def status = http.request(Method.GET,ContentType.JSON){req - >
response.success = {resp,json - >
result = json.toString()
new Success< String>(result)
}
response.'401'= {resp - >
final String errMsg =Not Authorized
new Failed(Failable.Fail.ACCESS_DENIED,errMsg)
}
response.failure = {resp - >
final String errMsg =General failure $ {resp.statusLine}
new Failed(Failable.Fail.UNKNOWN,errMsg)
}
}
}

我想要做的是找到一种方法来单元测试这个代码块。如果可能的话,我想嘲笑响应,所以我可以专门设置响应代码。有人可以告诉我一种方法吗?

解决方案

这是我的首选解决方案:

  class MockHTTPBuilder {
MockHTTPBuilder(string){}
MockHTTPBuilder(){}
def pleaseFail = false
def mockData = []
def request(a,b,c){
if(pleaseFail)[status:'500',data:mockData?:It failed :(]
else [status:'200',data:mockData?:'Yay :)]
}
}

以下是一些示例用法: http://groovyconsole.appspot.com/script/ 760001



或者,您可以对实际的httpClient实例进行元编程,并使其按预期工作(在测试期间强行失败或传递),但这有点儿更复杂。

This question is closely related to this question. The difference is that I'd like to follow the recommended approach of mocking the client. So, I have the following HTTPBuilder defined:

protected readUrl() {
    def http = new HTTPBuilder("http://example.com")
    def status = http.request(Method.GET, ContentType.JSON) {req ->
        response.success = {resp, json ->
            result = json.toString()
            new Success<String>(result)
        }
        response.'401' = {resp ->
            final String errMsg = "Not Authorized"
            new Failed(Failable.Fail.ACCESS_DENIED, errMsg)
        }
        response.failure = {resp ->
            final String errMsg = "General failure ${resp.statusLine}"
            new Failed(Failable.Fail.UNKNOWN, errMsg)
        }
    }
}

What I'd like to do is find a way to unit test this code block. I wanted to mock the response so I could specifically set the response codes, if possible. Could someone please show me a way to do this?

解决方案

This is my prefered solution:

class MockHTTPBuilder{
    MockHTTPBuilder(string){}
    MockHTTPBuilder(){}
    def pleaseFail = false
    def mockData = []
    def request(a, b, c){
        if(pleaseFail) [status:'500',data: mockData ?: "It failed :("]
        else [status:'200',data: mockData ?: "Yay :)"]
    }
}

Here's some sample usages: http://groovyconsole.appspot.com/script/760001

Alternatively, you can metaprogram the actual httpClient instance and make it behave as expected(forcebly failing or passing during test-time) but that's a little bit more complicated.

这篇关于Groovy HTTPBuilder模拟客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆