4

这个问题与这个问题密切相关。不同之处在于我想遵循模拟客户端的推荐方法。因此,我定义了以下 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)
        }
    }
}

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

4

1 回答 1

1

这是我的首选解决方案:

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 实例进行元编程并使其行为符合预期(在测试期间强制失败或通过),但这有点复杂。

于 2012-09-28T15:14:31.017 回答