简体   繁体   English

Groovy HTTPBuilder模拟客户端

[英]Groovy HTTPBuilder Mocking the Client

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: 所以,我定义了以下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)
        }
    }
}

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 以下是一些示例用法: 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. 或者,您可以对实际的httpClient实例进行元编程,并使其按预期运行(在测试时间内强制失败或传递),但这有点复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM