Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Integration tests use WireMock stubs written by hand, and production failed because the real downstream API changed a field name. How do you keep HTTP mocks honest, and how do you test timeouts and retries?

Hand-written stubs only describe what we believed the API looked like, so they drift when the provider changes. To keep them honest, I would add consumer-driven contract tests with Spring Cloud Contract or Pact, so the provider's build verifies the same expectations our stubs encode, and generate or refresh stubs from the provider's OpenAPI description or recorded traffic. For timeouts and retries, WireMock can delay responses with withFixedDelay, break connections with Fault.CONNECTION_RESET_BY_PEER and return a sequence of answers with scenarios; OkHttp's MockWebServer does the same with queued MockResponse objects, and verify(exactly(3), ...) checks the number of attempts.

Why this question is asked

This scenario is a classic: every test was green, and production broke on the first call after the provider renamed customerName to fullName. The tests were not wrong; they were testing our client against our own idea of the provider, and nothing connected that idea to reality. Interviewers ask it because the answer covers two different skills: keeping test doubles truthful over time, and testing the unhappy paths, like slow and failing dependencies, that cause most real outages. In this answer, we will see exactly why stubs drift, fix that with contracts and generated stubs, and then write fault tests for timeouts, connection resets and retries with WireMock and MockWebServer.

1Why Hand-Written Stubs Drift

A WireMock stub is a statement: 'when we call GET /customers/42, the provider answers with this JSON'. When we write it by hand, it is true on the day we copy it from the documentation or from a real response. After that, nothing checks it. The provider team renames a field, changes a type from number to string, makes a field optional, or adds a required header, and our stub still returns the old shape. Our tests stay green because they test our client against the stub, and the stub agrees with our client.

So the gap is not in WireMock; it is that the stub has a single owner, the consumer, and the provider never sees it. Keeping mocks honest means making the provider's build aware of what consumers expect, or making the stubs come from the provider.

2Fix 1: Consumer-Driven Contract Tests

In consumer-driven contract testing, the consumer writes down the requests it makes and the parts of the response it relies on. That record, the contract, is shared with the provider, and the provider's build runs it as a test against the real provider code. If the provider renames customerName, the contract test fails in the provider's pipeline, before the change is deployed, and the provider team sees exactly which consumer would break.

Spring Cloud Contract and Pact both work this way, with different emphasis. With Pact, the consumer's test generates the contract, called a pact file, while running against a Pact mock server, and the file is published to a broker for the provider to verify. With Spring Cloud Contract, contracts are typically written in a Groovy, YAML or Kotlin DSL in the provider's repository, often by consumers through pull requests; the provider's build turns them into tests, and also into WireMock stubs that consumers download and run with Stub Runner. Either way, the stubs the consumer tests against are the same expectations the provider verifies, so they cannot drift apart silently.

Step throughHow a contract catches the rename before production
Consumer buildContract brokerProvider build
publish contract: GET /customers/42 needs customerName
fetch contracts for customer-service
verify against real provider code: customerName missing
record verification failed
deployment blocked, provider team sees which consumer breaks

5 messages in order. Play them, or step through them one at a time.

The provider learns about the break in its own pipeline instead of from an incident.

3Fix 2: Generate or Record Stubs Instead of Writing Them

Where contract testing is not yet in place, we can still reduce drift by not writing stubs by hand. If the provider publishes an OpenAPI description, tools can generate stubs or validate our stubs against it, so a field that no longer exists in the schema fails our build. WireMock can also record real traffic: in record mode it proxies requests to a real provider environment and saves the responses as stub mappings, which we then commit and replay in tests.

Generated and recorded stubs still go stale if nobody refreshes them, so the refresh must be part of the process, for example a scheduled job that regenerates stubs from the latest provider specification and opens a pull request when they change. That turns a silent drift into a visible diff that someone has to review.

4Testing Timeouts and Connection Failures With WireMock

The second half of the question is the unhappy path. Most outages involving HTTP dependencies are not wrong JSON but slow or broken connections, and each needs a test. For a timeout, we make WireMock answer more slowly than the client's read timeout.

Java
// Client configured with a 1 second read timeout, e.g. through its request factory
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory();
factory.setReadTimeout(Duration.ofSeconds(1));
wm.stubFor(get(urlEqualTo("/customers/42"))
.willReturn(okJson("{\"id\":42,\"fullName\":\"Ann\"}").withFixedDelay(3_000))); // 3 s delay
assertThatThrownBy(() -> client.find(42))
.isInstanceOf(ResourceAccessException.class); // the read timed out after about 1 s
wm.stubFor(get(urlEqualTo("/customers/43"))
.willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))); // TCP reset
assertThatThrownBy(() -> client.find(43))
.isInstanceOf(ResourceAccessException.class); // I/O error on the connection

Notice that the test needs the client's timeout to be shorter than the delay; a client without a timeout would wait the full three seconds and succeed, which is a finding in itself, because production calls without timeouts can hang threads. WireMock also offers faults such as EMPTY_RESPONSE and chunked dribble delays that send the body slowly. The exact exception type depends on the client and its request factory, so assert on what your client actually throws, or better, on what your code returns to its caller, such as a fallback value.

5Testing Retries With Scenarios and Counting Attempts

A retry test needs the provider to fail and then succeed. WireMock scenarios are small state machines: each stub applies only in a named state and can move the scenario to the next state when it matches.

Java
String url = "/customers/42";
wm.stubFor(get(urlEqualTo(url)).inScenario("flaky").whenScenarioStateIs(Scenario.STARTED)
.willReturn(serviceUnavailable()).willSetStateTo("second")); // attempt 1: 503
wm.stubFor(get(urlEqualTo(url)).inScenario("flaky").whenScenarioStateIs("second")
.willReturn(serviceUnavailable()).willSetStateTo("third")); // attempt 2: 503
wm.stubFor(get(urlEqualTo(url)).inScenario("flaky").whenScenarioStateIs("third")
.willReturn(okJson("{\"id\":42,\"fullName\":\"Ann\"}"))); // attempt 3: 200
assertThat(client.find(42).fullName()).isEqualTo("Ann"); // succeeds after two retries
wm.verify(exactly(3), getRequestedFor(urlEqualTo(url))); // exactly 3 attempts, no more

verify(exactly(3), ...) is the important line. It catches a client that does not retry at all, which would fail on the first 503, and also a client that retries too eagerly, for example because two layers, a Resilience4j retry and an HTTP client retry, are both active and multiply the attempts. To check backoff, we can read the request journal with wm.getAllServeEvents() and compare the logged timestamps of the attempts, keeping the tolerances generous so the test does not become flaky itself; with a fake clock in the retry library, timing can even be checked exactly.

6The Same Tests With MockWebServer

OkHttp's MockWebServer takes a different approach that some teams prefer for client tests: instead of matching rules, it serves a queue of responses in order. Each enqueued MockResponse can set a status, body, headers, a body delay, a throttle that sends the body slowly, or a socket policy that disconnects at a chosen point. takeRequest() returns the recorded requests one by one, and getRequestCount() gives the number of attempts.

Java
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(503));
server.enqueue(new MockResponse().setResponseCode(503));
server.enqueue(new MockResponse().setBody("{\"id\":42,\"fullName\":\"Ann\"}")
.addHeader("Content-Type", "application/json"));
server.start();
// point the client at server.url("/").toString(), call find(42)
assertThat(server.getRequestCount()).isEqualTo(3); // 3 attempts

The queue style is very natural for retry sequences. The API shown is the classic okhttp3.mockwebserver one; OkHttp 5 introduced a mockwebserver3 package with a builder-style MockResponse, so check your version for the exact method names.

7Follow-up questions

If we have contract tests, do we still need WireMock fault tests?

Yes. Contracts check the shape of successful and error responses that both sides agree on. They do not test how our client behaves when the network is slow, a connection resets or the provider is overloaded. Those behaviours are ours to test, and WireMock or MockWebServer faults are the tool for it.

Pact or Spring Cloud Contract?

Pact suits organisations with mixed languages and a consumer-first workflow, since consumers in any language generate pacts and a broker coordinates verification. Spring Cloud Contract fits Spring-heavy organisations where contracts live with the provider and consumers use generated WireMock stubs through Stub Runner. Both solve the drift problem; the choice depends on who should own the contracts and the language mix.

8Conclusion

In this answer, we saw that hand-written stubs drift because only the consumer knows about them. Consumer-driven contracts with Spring Cloud Contract or Pact make the provider verify the same expectations, and stubs generated from OpenAPI descriptions or recorded traffic, refreshed on a schedule, reduce drift further. For the unhappy paths, WireMock's withFixedDelay, faults such as CONNECTION_RESET_BY_PEER and scenarios test timeouts, broken connections and retry sequences, and verify(exactly(3), ...) checks that the client made the right number of attempts. MockWebServer offers the same tests with a queue of responses.

What to say in the interviewAbout 90 seconds aloud

Open with

The root problem is that a hand-written stub is the consumer's belief about the API, and nothing checks it against the provider, so when the provider renamed the field our tests stayed green.

Then, if they want more

I'd fix that with consumer-driven contract tests. With Pact, our consumer test generates a pact file and publishes it to a broker, and the provider's build verifies it against the real code; with Spring Cloud Contract, contracts live with the provider, generate provider tests, and also generate WireMock stubs that we consume through Stub Runner.

Either way, the stubs we test against are the expectations the provider verifies, so a rename fails the provider's pipeline before deployment. Where contracts aren't in place yet, I'd generate stubs from the provider's OpenAPI or record real traffic with WireMock, and refresh them on a schedule so changes appear as a reviewed diff.

For timeouts and retries, I'd use WireMock faults. withFixedDelay longer than the client's read timeout tests the timeout, which also shows whether we even have one. Fault CONNECTION_RESET_BY_PEER tests broken connections. For retries, a scenario returns 503, 503, then 200, and I verify exactly three requests, which catches both no retry and double retry from two layers.

Backoff can be checked from the serve event timestamps. MockWebServer does the same with enqueued MockResponses and getRequestCount.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Integration tests use WireMock stubs written by hand, and production failed because the...": https://scrivio-interview-library.netlify.app/java/integration-testing/b27e1f98b9/