gpt4 book ai didi

unit-testing - Groovy HTTPBuilder 模拟客户端

转载 作者:行者123 更新时间:2023-12-02 03:56:11 27 4
gpt4 key购买 nike

这个问题与 this question 密切相关.不同之处在于我想遵循模拟客户端的推荐方法。因此,我定义了以下 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 实例进行元编程并使其行为符合预期(在测试期间强制失败或通过),但这有点复杂。

关于unit-testing - Groovy HTTPBuilder 模拟客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12534335/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com