Video in progress

Middle 🌱 Spring

How do you test a client that calls an external HTTP API without hitting the real service?

@RestClientTest brings up only the HTTP client layer, and with MockRestServiceServer you provide the expected request and a fake response. That way the URL, headers, JSON and error cases are checked quickly, with no network.

📖 Answer

Say CurrencyClient fetches exchange rates through RestClient.Builder. Going to the real API from a test is bad: it's slow, unstable, and CI may not even have network access.

@RestClientTest(components = CurrencyClient.class,
                properties = "currency.base-url=http://cbu.test")
class CurrencyClientTest {

    @Autowired CurrencyClient client;
    @Autowired MockRestServiceServer server;

    @Test
    void kursniOqiydi() {
        server.expect(requestTo("http://cbu.test/rates/USD"))
              .andExpect(method(HttpMethod.GET))
              .andRespond(withSuccess("""
                  {"code":"USD","rate":12650.50}""", MediaType.APPLICATION_JSON));

        assertThat(client.rate("USD")).isEqualByComparingTo("12650.50");
        server.verify();
    }

    @Test
    void server500QaytarsaOzExceptionimiz() {
        server.expect(requestTo("http://cbu.test/rates/USD")).andRespond(withServerError());

        assertThatThrownBy(() -> client.rate("USD"))
            .isInstanceOf(CurrencyUnavailableException.class);
    }
}

An important condition: the client must get the builder injected from Spring (RestClient.Builder in Boot 3.2+, RestTemplateBuilder before that). If it creates its own with RestClient.create(), MockRestServiceServer can't attach to it, and the test goes out to the real network.

What this test catches: a wrong URL or query parameter, a mistake in a JSON field name, turning 4xx/5xx into your own exception. It can't reliably check timeouts, though; for that you add a delay in WireMock or MockWebServer. MockRestServiceServer doesn't work for WebClient either, you need those tools.