MockRestServiceServer is a Spring testing utility that simulates HTTP responses for RestClient-based integrations. It intercepts client internals rather than serving real HTTP traffic, making it lighter than alternatives such as WireMock or MockServer. section 5.4
Because RestClient is immutable, connect the mock server through the RestClient.Builder. With @RestClientTest, Spring Boot automatically wires the service, mock server, and HTTP-client test infrastructure; pure Spring requires manual setup. section 5.4
Configure expectations and responses directly in each test:
- Match requests by query parameters, arbitrary request conditions, or custom URI inspection. section 5.4
- Return canned JSON, HTTP errors, custom status codes, headers, and response bodies. section 5.4
- Verify that expected requests occurred within configured counts; verification fails when requests are missing or excessive. section 5.4
Testing a RestClient service
@RestClientTest(components = { OpenMeteoWeatherDataService.class }) class OpenMeteoWeatherDataServiceTest { @Autowired OpenMeteoWeatherDataService service; @Autowired MockRestServiceServer mockServer; @Test void getWeatherData() { mockServer.expect(queryParam("latitude", "32.99")) .andExpect(queryParam("longitude", "-97.68")) .andRespond(withSuccess(""" { "current": { "temperature_2m": 3.1, "windspeed_10m": 52.0, "weathercode": 95 } } """, MediaType.APPLICATION_JSON)); var response = service.getCurrentWeather(32.99, -97.68); assertThat(response.temperature()).isEqualTo(3.1); } Use the same pattern with withBadRequest(), custom request predicates, or withStatus(...) to exercise failures and unusual responses. section 5.4
Figure 5.4 Customizations of a Service class using a RestClient for testing. From the point of view of the service under test, the HTTP client is a plain RestClient, with no special features. The server is exposed to the testing code for extra configuration.
The testing arrangement keeps the service-facing client plain while exposing the mock server for test-specific expectations and responses. section 5.4
