我正在尝试弄清楚如何为我将要编写的服务编写测试用例。
该服务将使用HTTPBuilder从某个URL请求响应。HTTPBuilder请求只需要检查响应是成功还是失败。服务实现将非常简单,如下所示:
boolean isOk() {
httpBuilder.request(GET) {
response.success = { return true }
response.failure = { return false }
}
}因此,我希望能够模拟HTTPBuilder,以便在测试中将响应设置为成功/失败,这样我就可以断言,当响应成功时,我的服务的isOk方法返回True,而当响应失败时,则返回False。
有人可以帮助我模拟HTTPBuilder请求并在GroovyTestCase中设置响应吗?
发布于 2012-02-02 02:59:16
下面是一个处理测试用例的模拟HttpBuilder的最小示例:
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。
编辑:下面是一个使用MockFor而不是模拟类的示例:
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
}https://stackoverflow.com/questions/9101084
复制相似问题