Search code examples
unit-testinggrailsgroovyhttpbuilder

Groovy HTTPBuilder Mocking the Client


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?


Solution

  • 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.