Groovy HTTPBuilder Dock Response

I am trying to figure out how to write my test cases for the service I'm going to write.

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

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

So, I want to be able to mock HTTPBuilder so that I can set the answer as successful / unsuccessful in my test, so I can argue that my isOk service isOk returns True when the response is successful and False when the response is a failure.

Can anyone help with how I can mock an HTTPBuilder request and set the response in GroovyTestCase?

+7
source share
1 answer

Here is a minimal HttpBuilder layout example that your test case will handle:

 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 causes a success closure, otherwise failure .

EDIT: here is an example of using MockFor instead of the 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 being tested } mock.use { assert isOk() == true } 
+10
source

All Articles