Groovy HTTPBuilder模拟响应

C0d*_*ack 10 groovy unit-testing httpbuilder

我想弄清楚如何为我要编写的服务编写我的测试用例.

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

boolean isOk() {
    httpBuilder.request(GET) {
        response.success = { return true }
        response.failure = { return false }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

ata*_*lor 12

这是一个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()
    }
}
Run Code Online (Sandbox Code Playgroud)

如果该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
}
Run Code Online (Sandbox Code Playgroud)