SunSear
SunSear

Reputation: 230

How to use MockFor to mock client on HttpBuilder?

I have some Grails production code I'd like to test and I've seen some examples of that here, see below. Problem is that I run into MissimgMethodExceptions on the client part of the HttpBuilder. This is the production code I'd like to test:

class RunkeeperActivitiesRetrieverService {
    def http = new RESTClient("http://api.runkeeper.com/")

    def getActivities() {
        http.client.clearRequestInterceptors();
        http.client.addRequestInterceptor(new HttpRequestInterceptor() {
            void process(HttpRequest httpRequest, HttpContext httpContext) {
                httpRequest.addHeader('Authorization', 'Bearer xxxxxxxxxx')
            }
        })
        //Do more with the httpBuilder
    }
}

I found some help on the topic of mocking the HTTPBuilder here: Groovy HTTPBuilder Mocking the Response and some on mocking interfaces in the groovy docs here: http://groovy.codehaus.org/Groovy+way+to+implement+interfaces

Using that code I came to this test code:

def mock = new MockFor(HTTPBuilder)
def impl = [
    addRequestInterceptor : {HttpRequestInterceptor interceptor -> println "hi 4"+interceptor},
    clearRequestInterceptors : {println "hi 88"}
            ]
def client = impl as HttpClient

mock.demand.getClient {return client}
mock.use{
    service.http = new HTTPBuilder()
    println service.getActivities()
}

Unfortunately my knowledge of Groovy is too limited to solve the exception that is thrown: groovy.lang.MissingMethodException: No signature of method: $Proxy15.clearRequestInterceptors() is applicable for argument types: () values: []

What am I missing here?

Upvotes: 4

Views: 922

Answers (1)

Brian Henry
Brian Henry

Reputation: 3171

You're casting impl to HttpClient - it doesn't appear the method in question is defined on that interface. Perhaps you mean to use some subclass of AbstractHttpClient.

Upvotes: 1

Related Questions