Groovy HTTPBuilder Mocking the Response
Asked Answered
R

1

10

I am trying to figure out how to write my Test cases for a service I am going to write.

The service will use HTTPBuilder to request a response from some URL. The HTTPBuilder request only needs to check the response for a success or failure. The service implementation will be be something as simple as:

boolean isOk() {
    httpBuilder.request(GET) {
        response.success = { return true }
        response.failure = { return false }
    }
}

So, I want to be able to mock the HTTPBuilder so that I can set the response to be either success/failure in my test so I can assert that my service's isOk method returns True when the response is a success and False, when the response is a failure.

Can any one help with how I can mock the HTTPBuilder request and set the response in a GroovyTestCase?

Reinareinald answered 1/2, 2012 at 18:20 Comment(0)
S
12

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
}
Schapira answered 1/2, 2012 at 18:59 Comment(4)
Thanks for the reply. I don't understand what will set 'result' to true/false. Also isn't this more like a Stub than a Mock?Reinareinald
You have to set result yourself when you set up the test. E.g. new MockHttpBuilder(result: true). I've added an alternative that uses groovy mocking.Schapira
Ataylor's response is good, I came up with pretty much the same implementation, except that I directly set the response status and then use it to execute the correct closure from the mapping. However this is truly Stub mocking. I think the correct approach is to mock the client which gives the response.Octodecillion
Can you give any example when the success and failure are actually returning some data ? Also does URI and header info makes any difference ?Ethnic

© 2022 - 2024 — McMap. All rights reserved.