Groovy HTTPBuilder Mocking the Response

a 夏天 提交于 2019-11-28 11:08:46

Here's a minimal example of a mock HttpBuilder that will handle your test case:

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.

EDIT: Here's an example using MockFor instead of a mock class:

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!