繁体   English   中英

Groovy HTTPBuilder模拟响应

[英]Groovy HTTPBuilder Mocking the Response

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

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

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

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

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

这是一个模拟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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM