[英]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. 我想弄清楚如何为我要编写的服务编写我的测试用例。
The service will use HTTPBuilder to request a response from some URL. 该服务将使用HTTPBuilder从某个URL请求响应。 The HTTPBuilder request only needs to check the response for a success or failure. HTTPBuilder请求只需要检查响应是否成功。 The service implementation will be be something as simple as: 服务实现将是这样简单:
boolean isOk() {
httpBuilder.request(GET) {
response.success = { return true }
response.failure = { return 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,以便我可以在我的测试中将响应设置为成功/失败,这样我就可以断言我的服务的isOk
方法在响应成功时返回True而在响应时返回False是失败的。
Can any one help with how I can mock the HTTPBuilder request and set the response in a GroovyTestCase? 任何人都可以帮助我如何模拟HTTPBuilder请求并在GroovyTestCase中设置响应?
Here's a minimal example of a mock HttpBuilder
that will handle your test case: 这是一个模拟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()
}
}
If the result
field is true, it'll invoke the success
closure, otherwise failure
. 如果result
字段为true,则它将调用success
闭包,否则将failure
。
EDIT: Here's an example using MockFor instead of a mock class: 编辑:这是一个使用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.