Groovy HTTPBuilder 模拟响应 [英] Groovy HTTPBuilder Mocking the Response
问题描述
我想弄清楚如何为我将要编写的服务编写测试用例.
I am trying to figure out how to write my Test cases for a service I am going to write.
该服务将使用 HTTPBuilder 从某个 URL 请求响应.HTTPBuilder 请求只需要检查响应是成功还是失败.服务实现将非常简单:
The service will use HTTPBuilder to request a response from some URL. The HTTPBuilder request only needs to check the response for a success or failure. The service implementation will be be something as simple as:
boolean isOk() {
httpBuilder.request(GET) {
response.success = { return true }
response.failure = { return false }
}
}
因此,我希望能够模拟 HTTPBuilder,以便我可以在测试中将响应设置为成功/失败,这样我就可以断言我的服务的 isOk
方法在当响应失败时,响应为成功和 False.
So, I want to be able to mock the HTTPBuilder so that I can set the response to be either success/failure in my test so I can assert that my service's isOk
method returns True when the response is a success and False, when the response is a failure.
有人可以帮助我如何模拟 HTTPBuilder 请求并在 GroovyTestCase 中设置响应吗?
Can any one help with how I can mock the HTTPBuilder request and set the response in a GroovyTestCase?
推荐答案
这是一个模拟 HttpBuilder
的最小示例,它将处理您的测试用例:
Here's a minimal example of a mock HttpBuilder
that will handle your test case:
class MockHttpBuilder {
def result
def requestDelegate = [response: [:]]
def request(Method method, Closure body) {
body.delegate = requestDelegate
body.call()
if (result)
requestDelegate.response.success()
else
requestDelegate.response.failure()
}
}
如果 result
字段为真,则调用 success
闭包,否则调用 failure
.
If the result
field is true, it'll invoke the success
closure, otherwise failure
.
这是一个使用 MockFor 而不是模拟类的示例:
Here's an example using MockFor instead of a mock class:
import groovy.mock.interceptor.MockFor
def requestDelegate = [response: [:]]
def mock = new MockFor(HttpBuilder)
mock.demand.request { Method method, Closure body ->
body.delegate = requestDelegate
body.call()
requestDelegate.response.success() // or failure depending on what's being tested
}
mock.use {
assert isOk() == true
}
这篇关于Groovy HTTPBuilder 模拟响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!