Microservice architecture as a whole has more inbound and outbound communication than monolithic systems. Where monoliths might have one request that performs several major actions behind the scenes, microservices very easily could split that up across multiple requests. Sometimes you will need services to communicate with each other directly. So, the question becomes: how do you test communication across microservice boundaries?

Let’s say that we have two microservices: “Microservice A” and “Microservice B”. Microservice A communicates with Microservice B via a REST endpoint that is owned by Microservice B.

In this tutorial, we will review how this communication can be tested from the perspective of the calling service (Microservice A).

If using the blocking RestTemplate, Spring provides MockRestServiceServer for mocking in tests. But as of version 5.0, Spring recommends using WebClient as a non-blocking, modern alternative to RestTemplate. However, there is no Spring-provided solution to mock the WebClient in tests. Instead, we will have to look to a third party library to provide this functionality, namely: MockWebServer.

Step 1: Prerequisites

Use Okhttp3 MockWebServer library. Include the following to your maven pom.xml:

Step 2: Writing the Tests

For testing both outbound request and inbound response you will need to add and initialize mock web server property to your test class:

First, test the outbound request from A to B:

In the example code below, we will be attempting to apply an offer.

  1. Make your method call that sends the request.
  2. Grab the request from the mock server.
  3. Verify the contents of the request. This may include the url or the method (POST, GET, PUT, etc.) that was used. Of particular interest is the body that was sent with the request, which can be verified as demonstrated in the example code below. We are taking the request as a string and using Jackson’s ObjectMapper class to map the request string to an object. You can also convert to a Map. Then we are using AssertJ to verify the values of the request object.

Full test:

Next, test the inbound response from B to A:

  1. Queue up a response from your mock web server. This will put your response on the mock server’s queue.
    1. Note: You can add multiple responses to this queue which will be provided in typical sequential fashion, FIFO (First In, First Out).
  2. Make your method call that sends the request.
  3. Take the response from your service and verify that it matches what you expect. You could have business logic that utilizes the response to which you can add further verification.

Full test:


For providing testing across microservice boundaries, MockWebServer provides a simple, easy-to-implement option for those wanting to test service-to-service communications. Further information can be found directly on the MockWebServer’s Github page: https://github.com/square/okhttp/tree/master/mockwebserver.