Video in progress

Middle 🧪 Testing

If your service calls an external HTTP API, how do you test that integration?

Instead of mocking the client class, it's better to start a fake HTTP server: WireMock or Spring's MockRestServiceServer. Then the URL, headers, JSON parsing, timeouts and handling of 5xx errors are all checked through the real HTTP layer.

📖 Answer

If you @Mock the PaymentClient, the things inside it that break most often go untested: a wrong path, a forgotten Authorization header, a field name in the JSON, the readTimeout setting.

With WireMock:

@SpringBootTest
@EnableWireMock(@ConfigureWireMock(name = "payment", baseUrlProperties = "payment.base-url"))
class PaymentClientIT {

    @InjectWireMock("payment") WireMockServer payment;
    @Autowired PaymentClient client;

    @Test
    void provayder_503_qaytarsa_qayta_urinadi() {
        payment.stubFor(post("/v1/charge").inScenario("retry")
            .willReturn(serviceUnavailable()).willSetStateTo("ok"));
        payment.stubFor(post("/v1/charge").inScenario("retry").whenScenarioStateIs("ok")
            .willReturn(okJson("{\"status\":\"APPROVED\"}")));

        assertEquals("APPROVED", client.charge(order).status());
        payment.verify(2, postRequestedFor(urlEqualTo("/v1/charge")));
    }
}

(@EnableWireMock comes from the wiremock-spring-boot library; you can also do it with a plain WireMockExtension.)

You can also simulate a slow response with withFixedDelay(3000) and check that the timeout works correctly; the most painful prod bugs come from exactly here.

If you only have a RestClient/RestTemplate and want a light test with no Spring context, @RestClientTest + MockRestServiceServer is enough.

One limit: WireMock stubs are your own assumptions. If the provider changes its response format, the tests stay green. Contract tests close that gap.