Video in progress
How do you test client code that depends on another HTTP service? How do you simulate a slow response or a 503?
I bring up a real HTTP server with WireMock and point the client at it. That way serialization, headers, timeouts and retries are checked through the real network layer; when you replace the client with a mock bean, none of this gets tested.
📖 Answer
Mocking the client interface (@MockitoBean PaymentClient, @MockBean before Boot 3.4) is fast, but it only answers "did the business code call the client". On prod the bugs are elsewhere: the URL is wrong, a JSON field name doesn't match, the timeout isn't configured, the retry doesn't work on a 503.
With WireMock:
@SpringBootTest(properties = "payment.base-url=http://localhost:8089")
@WireMockTest(httpPort = 8089)
class PaymentClientTest {
@Autowired PaymentClient client;
@Test
void failsOnSlowResponse() {
stubFor(post("/payments")
.willReturn(okJson("{\"id\":\"p1\"}").withFixedDelay(3000)));
assertThatThrownBy(() -> client.charge(request()))
.hasRootCauseInstanceOf(SocketTimeoutException.class);
}
@Test
void retriesAfter503() {
stubFor(post("/payments").inScenario("retry")
.whenScenarioStateIs(STARTED).willReturn(serviceUnavailable())
.willSetStateTo("ok"));
stubFor(post("/payments").inScenario("retry")
.whenScenarioStateIs("ok").willReturn(okJson("{\"id\":\"p1\"}")));
assertThat(client.charge(request()).id()).isEqualTo("p1");
verify(2, postRequestedFor(urlEqualTo("/payments")));
}
}
The first test passes only if the client's read timeout is under 3 seconds, so it also verifies that the timeout is configured.
Other useful stubs: aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER) for a dropped connection, and aResponse().withStatus(429).withHeader("Retry-After", "2") for a rate limit.
One limitation: you wrote the stub yourself, and the real service may respond differently. These tests don't replace contract tests, but they reliably check the client's own behavior (timeout, retry, mapping errors).
Sign up to mark studied questions and save your progress.