Stubbing Asynchronous Http Services using Wiremock

Wiremock is simple library which can be used to stub Http Services. It is a handy tool when you want to write unit tests against some Http service(eg: Http REST web service). It has direct support for JUnit using @Rule feature. We can write unit tests to stub different http requests and verify those requests and responses very easily.

One weakness of wiremock was it only supported synchronous  http request mocking(i.e: You send the request and stubbed wiremock server send the response). But I wanted to mock Asynchronous REST server. In asynchronous scenario in addition direct http response, server is initiating another call back request to the server. This method is commonly used by web service operations which take lots of time to process. Flow of such operation would look like follows.

When a client want to get some operation done;
  1) Client sends the request to the server
  2) Server accept that request and give that accepted response as direct http response
  3) Server do the processing and send the actual result as a new http request to the client

This feature is implemented in my wiremock forked repository. Still this is not being merged to main wiremock repository. So if you are interested in this you'll have to clone my forked repo, build it locally and publish the jar file to your local maven repository.

Stubbing asynchronous request is easy.


In most asynchronous http services, some kind of Id is being used to map original request with the asynchronous response. There can be two ways of doing this.
  1) Server generates transactionId and sends it with the immediate response
  2) Client sends the transactionId and server echo that when it sends back asynchronous response

If you want to use the second method with wiremock, you can use setEchoField method.

At the moment there is a one limitation with this. You can only use this facility with JSON requests and responses.

You can find the complete test class at github.
 

Reader Comments

Thanks for this post but the method .withCallbackRequest() and aCallbackRequestTo() I could not find. Could you pls explain me at j.basu@yahoo.com
Jayanta

@Jay
This feature in not merged with the main Wiremock project. As I've mentioned in the blog, it is in my forked wiremock repository https://github.com/sandarenu/wiremock

Good Post. I want to use this. Cloned your repository.
While building, it throws an error:
./gradlew

Exception in thread "main" java.lang.NoClassDefFoundError: org/gradle/wrapper/GradleWrapperMain

Good Post. I want to use this. Can you share one sample mapping file with callbacks



Tribune to Heros

Tribune to Heros
We will never forget the sacrifices you made to protect our country....

Subscribe


Get Google Toolbar Button

Enter your email address:

Delivered by FeedBurner