Groovy HTTPBuilder Mocking the Client

无人久伴 提交于 2019-12-10 10:03:55

问题


This question is closely related to this question. The difference is that I'd like to follow the recommended approach of mocking the client. So, I have the following HTTPBuilder defined:

protected readUrl() {
    def http = new HTTPBuilder("http://example.com")
    def status = http.request(Method.GET, ContentType.JSON) {req ->
        response.success = {resp, json ->
            result = json.toString()
            new Success<String>(result)
        }
        response.'401' = {resp ->
            final String errMsg = "Not Authorized"
            new Failed(Failable.Fail.ACCESS_DENIED, errMsg)
        }
        response.failure = {resp ->
            final String errMsg = "General failure ${resp.statusLine}"
            new Failed(Failable.Fail.UNKNOWN, errMsg)
        }
    }
}

What I'd like to do is find a way to unit test this code block. I wanted to mock the response so I could specifically set the response codes, if possible. Could someone please show me a way to do this?


回答1:


This is my prefered solution:

class MockHTTPBuilder{
    MockHTTPBuilder(string){}
    MockHTTPBuilder(){}
    def pleaseFail = false
    def mockData = []
    def request(a, b, c){
        if(pleaseFail) [status:'500',data: mockData ?: "It failed :("]
        else [status:'200',data: mockData ?: "Yay :)"]
    }
}

Here's some sample usages: http://groovyconsole.appspot.com/script/760001

Alternatively, you can metaprogram the actual httpClient instance and make it behave as expected(forcebly failing or passing during test-time) but that's a little bit more complicated.



来源:https://stackoverflow.com/questions/12534335/groovy-httpbuilder-mocking-the-client

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