Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Using WireMock in a Spring Boot test, stub a payment provider that returns 200 for one card and a 503 with a 2 second delay for another, and point the client at it.

We start WireMock on a dynamic port with the WireMock JUnit extension (or @WireMockTest, or the Testcontainers WireMock module), and point the application's payment client at it with @DynamicPropertySource. One stub matches a POST to /charges whose JSON body has card 4242 and returns 200 with okJson(...); a second matches another card and returns a 503 after withFixedDelay(2000), which lets us test timeouts and retries. Finally, we verify the requests WireMock received, for example that each charge carried an Idempotency-Key header.

Why this question is asked

Almost every Spring Boot service calls some external API, and the code that handles slow or failing responses is often the least tested part of the system. Testing against the real provider's sandbox is slow and cannot produce a 503 on demand. Interviewers ask for this exercise to see whether we can build a realistic, deterministic test for an HTTP client, including the unhappy paths. In this answer, we will recap what WireMock does, look at the client under test, start WireMock and connect the client to it, write both stubs, test the success, the timeout and the retries, and verify what was sent.

1A Quick Recap of WireMock

WireMock is an HTTP server we control from our test. We tell it which requests to expect and what to answer, and it answers exactly that. Each instruction is a stub: a request pattern, such as POST to /charges with a JSON body containing a given card number, and a response, such as status 200 with a JSON body, optionally after a delay.

Because WireMock is a real HTTP server on a real port, our application code does not know it is being tested. The real RestClient, the real JSON mapping and the real timeout settings are all exercised. That is the difference from mocking the client class with Mockito, which skips all of that.

2The Client Under Test

Here is a small payment client using Spring's RestClient, with a one-second read timeout. The base URL comes from a property, which is what lets the test redirect it.

Java
@Component
class PaymentClient {
private final RestClient rest;
PaymentClient(RestClient.Builder builder, @Value("${payments.base-url}") String baseUrl) {
var factory = new JdkClientHttpRequestFactory();
factory.setReadTimeout(Duration.ofSeconds(1));
this.rest = builder.baseUrl(baseUrl).requestFactory(factory).build();
}
ChargeResult charge(String card, long amountCents, String idempotencyKey) {
return rest.post().uri("/charges")
.header("Idempotency-Key", idempotencyKey)
.contentType(MediaType.APPLICATION_JSON)
.body(Map.of("card", card, "amountCents", amountCents))
.retrieve()
.body(ChargeResult.class);
}
}
record ChargeResult(String id, String status) {}

Notice that the timeout is shorter than the 2-second delay we will configure. That is deliberate: the slow stub lets us check that our client gives up after one second instead of hanging a request thread.

3Starting WireMock and Pointing the Client at It

The WireMock JUnit 5 extension starts a server before the tests and stops it afterwards. A dynamic port avoids clashes when builds run in parallel. Because Spring reads properties when it builds the context, we pass the port through @DynamicPropertySource, which runs before the context starts and can read the extension's base URL.

Java
@SpringBootTest
class PaymentClientTest {
@RegisterExtension
static WireMockExtension provider = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort())
.build();
@DynamicPropertySource
static void paymentProperties(DynamicPropertyRegistry registry) {
registry.add("payments.base-url", provider::baseUrl); // e.g. http://localhost:53211
}
@Autowired PaymentClient client;
}

Both members are static because the extension must exist before Spring creates the context, and @DynamicPropertySource methods must be static. The method reference provider::baseUrl is evaluated lazily, once the server has its port. Alternatives are the @WireMockTest annotation, which is convenient for tests without Spring, and the Testcontainers WireMock module, which runs WireMock in a Docker container when we want the same stub files in tests and in local environments.

4Stubbing Success and a Slow 503

Now the two stubs. The first matches a POST to /charges whose JSON body has card equal to 4242. The second matches card 0002 and returns 503 Service Unavailable after a 2-second delay.

Java
@BeforeEach
void stubs() {
provider.stubFor(post(urlEqualTo("/charges"))
.withRequestBody(matchingJsonPath("$.card", equalTo("4242")))
.willReturn(okJson("{\"id\":\"ch_1\",\"status\":\"succeeded\"}")));
provider.stubFor(post(urlEqualTo("/charges"))
.withRequestBody(matchingJsonPath("$.card", equalTo("0002")))
.willReturn(aResponse().withStatus(503).withFixedDelay(2000)));
}
Step throughThe two stubbed calls
TestPaymentClientWireMock
charge("4242", 1500, key-1)
POST /charges card=4242
200 {id: ch_1, status: succeeded}
ChargeResult(ch_1, succeeded)
charge("0002", 1500, key-2)
POST /charges card=0002
read timeout after 1 s
ResourceAccessException
503 after 2 s, too late

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

The client gives up after one second, before the slow 503 arrives.

matchingJsonPath checks one field of the JSON body without caring about the rest, so the stub does not break if we add a field to the request. okJson sets status 200, the JSON content type and the body. withFixedDelay(2000) makes WireMock wait 2,000 milliseconds before answering. If no stub matches, WireMock returns 404 and prints a list of near misses, which makes typos in stubs quick to find.

5Testing the Outcomes and Verifying Requests

With the stubs in place, the tests check what our code does with each answer, and then ask WireMock what it received.

Java
@Test
void successfulChargeReturnsTheProviderId() {
ChargeResult result = client.charge("4242", 1500, "key-1");
assertThat(result.status()).isEqualTo("succeeded"); // passes
provider.verify(postRequestedFor(urlEqualTo("/charges"))
.withHeader("Idempotency-Key", equalTo("key-1"))
.withRequestBody(matchingJsonPath("$.amountCents", equalTo("1500"))));
}
@Test
void slowProviderTimesOutAfterOneSecond() {
long start = System.nanoTime();
assertThatThrownBy(() -> client.charge("0002", 1500, "key-2"))
.isInstanceOf(ResourceAccessException.class); // read timed out
assertThat(Duration.ofNanos(System.nanoTime() - start)).isLessThan(Duration.ofMillis(1800));
}
// With a retry (for example Spring Retry, 3 attempts) around charge():
// provider.verify(3, postRequestedFor(urlEqualTo("/charges"))
// .withHeader("Idempotency-Key", equalTo("key-2"))); // same key on every attempt

The first test checks the mapped result and that the request carried the idempotency key and the amount, which are what the provider depends on. The second checks that the client gave up after the timeout rather than waiting the full 2 seconds; in Spring, a read timeout surfaces as ResourceAccessException. If we raise the timeout above 2 seconds, the client would receive the 503 instead and RestClient would throw HttpServerErrorException.ServiceUnavailable, which is the case to test if our retry logic reacts to status codes.

The commented lines show the most valuable verification of all. When we add retries, we check both the number of attempts and that every attempt used the same Idempotency-Key, because a retry with a new key could charge the customer twice.

6Follow-up questions

Why not mock PaymentClient with Mockito instead?

Mocking the client skips the HTTP layer: the JSON mapping, the headers, the timeout and the error handling are never exercised, and those are where integration bugs live. WireMock tests the real client against a real HTTP server, while staying fast and deterministic.

How do you avoid stubs from one test affecting another?

The WireMock extension resets stubs and the request journal between tests by default, and defining stubs in @BeforeEach or in each test keeps them local. Check your WireMock version's defaults if you share one server across classes.

When would you use the Testcontainers WireMock module?

When we want the same stub mappings, stored as JSON files, to be used by automated tests and by developers running the service locally, or when the service under test also runs in a container. It costs a container start, so for plain unit-style client tests the in-process extension is faster.

7Conclusion

In this answer, we tested a Spring Boot payment client against WireMock. We started WireMock on a dynamic port with its JUnit extension and pointed the client at it with @DynamicPropertySource, stubbed a 200 for card 4242 with matchingJsonPath and okJson, and a 503 with a 2-second fixed delay for another card. We then checked the success result, a read timeout after one second, and verified the requests WireMock received, including the idempotency key on every retry.

What to say in the interviewAbout 80 seconds aloud

Open with

I would use WireMock, which is a real HTTP server controlled from the test, so the real RestClient, JSON mapping and timeouts are exercised. In a @SpringBootTest I register the WireMock JUnit extension as a static field with a dynamic port, and in a static @DynamicPropertySource method I set payments.base-url to the extension's base URL, so the client talks to WireMock.

Then, if they want more

Then I write two stubs. The first is stubFor post urlEqualTo /charges, with withRequestBody matchingJsonPath dollar dot card equalTo 4242, returning okJson with an id and status succeeded. The second matches a different card and returns aResponse with status 503 and withFixedDelay of 2000 milliseconds.

In the tests I check that the success case maps to a ChargeResult with status succeeded.

For the slow card, my client has a one-second read timeout, so I expect a ResourceAccessException within about a second rather than a two-second wait; if I wanted to test handling of the 503 itself, I would raise the timeout and expect the service-unavailable exception.

Finally I use verify with postRequestedFor to check the request carried the Idempotency-Key header and the right amount, and with retries I verify the number of attempts and that each one reused the same key, so a retry can never double charge.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 5
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 "Using WireMock in a Spring Boot test, stub a payment provider that returns 200 for one...": https://scrivio-interview-library.netlify.app/java/test-strategy/660d5dce81/