我试图弄清楚如何为要编写的服务编写测试用例。
该服务将使用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
}
关于unit-testing - Groovy HTTPBuilder模拟响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9101084/