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?

Answers


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.


Need Your Help

Win32: How to get window from DC (the reverse of GetDC)

winapi gdi device-context

Is there a way to get a window handle to the window owning a win32 DC? Or any other sort of information that might be useful for identifying the window, like DC width and height?

fsolve always returning the guess/estimate

python scipy equation-solving

I'm using scipy's optimize.fsolve function for the first time to find the roots to an equation. The problem is that whatever number I use as the guess/estimate value is what I get back as my answer...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.