@RestClientTest is a Spring Boot test slice for code that calls external HTTP services through RestClient. It loads the selected client-facing components and HTTP-client testing infrastructure instead of a full application context. Add spring-boot-starter-restclient-test as a test-scoped dependency. section 5.4
Name the components under test explicitly: slice scanning cannot infer which beans need testing from a RestClient.Builder constructor parameter. The slice supplies a MockRestServiceServer and a RestClientCustomizer that connects the default Boot client to that server. If the selected component needs other services, provide them through test configuration, @MockitoBean, or @TestBean; they are not loaded automatically. section 5.4
Listing 5.7 Using the @RestClientTest annotation.
@RestClientTest(components = { OpenMeteoWeatherDataService.class }) #1
class OpenMeteoWeatherDataServiceTest {
@Autowired
private OpenMeteoWeatherDataService service; #2
@Autowired
private MockRestServiceServer mockServer; #3
// ... tests ...
}
A focused test names its service in @RestClientTest, then injects both that service and MockRestServiceServer. section 5.4
Test a weather-service request
Set a mock-server expectation for the latitude and longitude query parameters, respond with JSON, then call the service and assert its mapped weather values. A separate test can return HTTP 400 and assert that the service throws IllegalArgumentException. Request matchers and response creators can also be customized; mockServer.verify() checks whether configured expectations were met. section 5.4
Choose this slice when the HTTP integration is the subject of the test. A full-context test is an alternative when broader application wiring matters. Slices can give focused feedback, but accumulating too many distinct slices risks context thrashing. section 5.8
