Groovy HTTPBuilder模拟响应

时间:2012-02-01 18:20:22

标签: unit-testing groovy httpbuilder

我正在试图弄清楚如何编写我要写的服务的测试用例。

该服务将使用HTTPBuilder从某个URL请求响应。 HTTPBuilder请求只需要检查响应是否成功。服务实现将是如此简单:

boolean isOk() {
    httpBuilder.request(GET) {
        response.success = { return true }
        response.failure = { return false }
    }
}

所以,我希望能够模拟HTTPBuilder,以便我可以在我的测试中将响应设置为成功/失败,这样我就可以断言我的服务的isOk方法在响应为a时返回True成功和错误,当响应失败时。

任何人都可以帮助我如何模拟HTTPBuilder请求并在GroovyTestCase中设置响应吗?

1 个答案:

答案 0 :(得分:11)

以下是处理测试用例的模拟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字段为true,则会调用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
}