1. Introduction

Spring WebClient is a non-blocking, reactive client for performing HTTP requests, and WireMock is a powerful tool for simulating HTTP-based APIs.

In this tutorial, we’ll see how we can utilize WireMock API to stub HTTP-based client requests when using WebClient. By simulating the behavior of external services, we can ensure that our application can handle and process the external API responses as expected.

We’ll add the required dependencies, followed by a quick example. Finally, we’ll utilize the WireMock API to write some integration tests for some cases.

2. Dependencies and Example

First, let’s ensure we have the necessary dependencies in our Spring Boot project.

We’ll need spring-boot-starter-flux for WebClient and spring-cloud-starter-wiremock for the WireMock server*.*  Let’s add them in our pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-contract-wiremock</artifactId>
    <version>4.1.2</version>
    <scope>test</scope>
</dependency>

Now, let’s introduce a simple example where we’ll communicate with an external weather API to fetch weather data for a given city. Let’s define the WeatherData POJO next:

public class WeatherData {
    private String city;
    private int temperature;
    private String description;
    ....
   //constructor
   //setters and getters
}

We want to test this functionality using WebClient and WireMock for integration testing.

3. Integration Testing Using the WireMock API

Let’s set up the Spring Boot test class first with WireMock and WebClient:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWireMock(port = 0)
public class WeatherServiceIntegrationTest {

    @Autowired
    private WebClient.Builder webClientBuilder;

    @Value("${wiremock.server.port}")
    private int wireMockPort;

    // Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();
  ....
  ....
}

Notably, @AutoConfigureWireMock automatically starts a WireMock server on a random port. Additionally, we’re creating a WebClient instance with the WireMock server’s base URL. Any request via webClient now goes to the WireMock server instance and if the correct stub exists, the appropriate response is sent.

3.1. Stubbing Response With Success and JSON Body

Let’s start by stubbing an HTTP call with a JSON request with the server returning 200 OK:

@Test
public void  givenWebClientBaseURLConfiguredToWireMock_whenGetRequestForACity_thenWebClientRecievesSuccessResponse() {
    // Stubbing response for a successful weather data retrieval
    stubFor(get(urlEqualTo("/weather?city=London"))
      .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"city\": \"London\", \"temperature\": 20, \"description\": \"Cloudy\"}")));

    // Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();

    // Fetch weather data for London
    WeatherData weatherData = webClient.get()
      .uri("/weather?city=London")
      .retrieve()
      .bodyToMono(WeatherData.class)
      .block();
    assertNotNull(weatherData);
    assertEquals("London", weatherData.getCity());
    assertEquals(20, weatherData.getTemperature());
    assertEquals("Cloudy", weatherData.getDescription());
}

When a request to /weather?city=London is sent via WebClient with a base URL pointing to the WireMock port, the stubbed response is returned, which is then used in our system as required.

3.2. Simulating Custom Headers

Sometimes an HTTP request requires custom headers. WireMock can match the custom headers to provide an appropriate response.

Let’s create a stub containing two headers, one is Content-Type and the other is X-Custom-Header with the value “baeldung-header”:

@Test
public void givenWebClientBaseURLConfiguredToWireMock_whenGetRequest_theCustomHeaderIsReturned() {
    //Stubbing response with custom headers
    stubFor(get(urlEqualTo("/weather?city=London"))
      .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withHeader("X-Custom-Header", "baeldung-header")
        .withBody("{\"city\": \"London\", \"temperature\": 20, \"description\": \"Cloudy\"}")));

    //Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();

    //Fetch weather data for London
    WeatherData weatherData = webClient.get()
      .uri("/weather?city=London")
      .retrieve()
      .bodyToMono(WeatherData.class)
      .block();

    //Assert the custom header
    HttpHeaders headers = webClient.get()
      .uri("/weather?city=London")
      .exchange()
      .block()
      .headers();  
    assertEquals("baeldung-header", headers.getFirst("X-Custom-Header"));
}

The WireMock server responds with the stubbed weather data for London, including the custom header.

3.3. Simulating Exceptions

Another useful case to test is when the external service returns an exception. WireMock server lets us simulate these exceptional scenarios to see our system behavior under such conditions:

@Test
public void givenWebClientBaseURLConfiguredToWireMock_whenGetRequestWithInvalidCity_thenExceptionReturnedFromWireMock() {
    //Stubbing response for an invalid city
    stubFor(get(urlEqualTo("/weather?city=InvalidCity"))
      .willReturn(aResponse()
        .withStatus(404)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"error\": \"City not found\"}")));

    // Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();

   // Fetch weather data for an invalid city
    WebClientResponseException exception = assertThrows(WebClientResponseException.class, () -> {
      webClient.get()
      .uri("/weather?city=InvalidCity")
      .retrieve()
      .bodyToMono(WeatherData.class)
      .block();
});

Importantly, here we’re testing whether the WebClient correctly handles an error response from the server when querying weather data for an invalid city. It verifies that a WebClientResponseException is thrown when making a request to /weather?city=InvalidCity, ensuring proper error handling in the application.

3.4. Simulating Response With Query Parameter

Frequently, we have to send requests with query parameters. Let’s create a stub for that next:

@Test
public void givenWebClientWithBaseURLConfiguredToWireMock_whenGetWithQueryParameter_thenWireMockReturnsResponse() {
    // Stubbing response with specific query parameters
    stubFor(get(urlPathEqualTo("/weather"))
      .withQueryParam("city", equalTo("London"))
      .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"city\": \"London\", \"temperature\": 20, \"description\": \"Cloudy\"}")));

    //Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();

    WeatherData londonWeatherData = webClient.get()
      .uri(uriBuilder -> uriBuilder.path("/weather").queryParam("city", "London").build())
      .retrieve()
      .bodyToMono(WeatherData.class)
      .block();
    assertEquals("London", londonWeatherData.getCity());
}

3.5. Simulating Dynamic Responses

Let’s look at an example where we generate a random temperature value between 10 and 30 degrees in the response body:

@Test
public void givenWebClientBaseURLConfiguredToWireMock_whenGetRequest_theDynamicResponseIsSent() {
    //Stubbing response with dynamic temperature
    stubFor(get(urlEqualTo("/weather?city=London"))
      .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"city\": \"London\", \"temperature\": ${randomValue|10|30}, \"description\": \"Cloudy\"}")));

    //Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();

    //Fetch weather data for London
    WeatherData weatherData = webClient.get()
      .uri("/weather?city=London")
      .retrieve()
      .bodyToMono(WeatherData.class)
      .block();

    //Assert temperature is within the expected range
    assertNotNull(weatherData);
    assertTrue(weatherData.getTemperature() >= 10 && weatherData.getTemperature() <= 30);
}

3.6. Simulating Asynchronous Behavior

Here, we’ll try to mimic real-world scenarios where services may experience latency or network delays, by introducing a simulated delay of one second in the response:

@Test
public void  givenWebClientBaseURLConfiguredToWireMock_whenGetRequest_thenResponseReturnedWithDelay() {
    //Stubbing response with a delay
    stubFor(get(urlEqualTo("/weather?city=London"))
      .willReturn(aResponse()
        .withStatus(200)
        .withFixedDelay(1000) // 1 second delay
        .withHeader("Content-Type", "application/json")
        .withBody("{\"city\": \"London\", \"temperature\": 20, \"description\": \"Cloudy\"}")));

    //Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();

    //Fetch weather data for London
    long startTime = System.currentTimeMillis();
    WeatherData weatherData = webClient.get()
      .uri("/weather?city=London")
      .retrieve()
      .bodyToMono(WeatherData.class)
      .block();
    long endTime = System.currentTimeMillis();

    assertNotNull(weatherData);
    assertTrue(endTime - startTime >= 1000); // Assert the delay
}

Essentially, we want to ensure that the application handles delayed responses gracefully without timing out or encountering unexpected errors.

3.7. Simulating Stateful Behavior

Next, let’s incorporate the use of WireMock scenarios to simulate stateful behavior. The API allows us to configure the stub to respond differently when called multiple times depending upon the state:

@Test
public void givenWebClientBaseURLConfiguredToWireMock_whenMulitpleGet_thenWireMockReturnsMultipleResponsesBasedOnState() {
    //Stubbing response for the first call
    stubFor(get(urlEqualTo("/weather?city=London"))
      .inScenario("Weather Scenario")
      .whenScenarioStateIs("started")
      .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"city\": \"London\", \"temperature\": 20, \"description\": \"Cloudy\"}"))
    .willSetStateTo("Weather Found"));

    // Stubbing response for the second call
    stubFor(get(urlEqualTo("/weather?city=London"))
      .inScenario("Weather Scenario")
      .whenScenarioStateIs("Weather Found")
      .willReturn(aResponse()
        .withStatus(200)
        .withHeader("Content-Type", "application/json")
        .withBody("{\"city\": \"London\", \"temperature\": 25, \"description\": \"Sunny\"}")));

    //Create WebClient instance with WireMock base URL
    WebClient webClient = webClientBuilder.baseUrl("http://localhost:" + wireMockPort).build();

    //Fetch weather data for London
    WeatherData firstWeatherData = webClient.get()
      .uri("/weather?city=London")
      .retrieve()
      .bodyToMono(WeatherData.class)
      .block();

  //Assert the first response
  assertNotNull(firstWeatherData);
  assertEquals("London", firstWeatherData.getCity());
  assertEquals(20, firstWeatherData.getTemperature());
  assertEquals("Cloudy", firstWeatherData.getDescription());

  // Fetch weather data for London again
  WeatherData secondWeatherData = webClient.get()
    .uri("/weather?city=London")
    .retrieve()
    .bodyToMono(WeatherData.class)
    .block();

  // Assert the second response
  assertNotNull(secondWeatherData);
  assertEquals("London", secondWeatherData.getCity());
  assertEquals(25, secondWeatherData.getTemperature());
  assertEquals("Sunny", secondWeatherData.getDescription());
}

Essentially, we defined two stub mappings for the same URL  within the same scenario named “Weather Scenario“. However, we’ve configured the first stub to respond with weather data for London with a temperature of 20°C and a description of “Cloudy” when the scenario is in the “started” state.

After responding, it transitions the scenario state to “Weather Found“. The second stub is configured to respond with different weather data with a temperature of 25°C and a description of “Sunny” when the scenario is in the “Weather Found” state.

4. Conclusion

In this article, we’ve discussed the basics of integration testing with Spring WebClient and WireMock. WireMock provides extensive capabilities for stubbing HTTP responses to simulate various scenarios.

We quickly looked at some of the frequently encountered scenarios for simulating HTTP response in combination with WebClient.

As always, the full implementation of this article can be found over on GitHub.