Quick revision
The short answer
We start WireMock on a dynamic port with the JUnit 5 WireMockExtension, register its base URL as the client's base-url property with @DynamicPropertySource so the RestClient bean calls the stub, and stub GET /customers/42 with okJson(...). After calling our client, wm.verify(getRequestedFor(urlEqualTo("/customers/42")).withHeader("Authorization", matching("Bearer .*"))) checks that the request really carried the header. The dynamic port lets several test classes run in parallel without clashing.
What to remember
In this answer, we wrote a Spring Boot test for an HTTP client with WireMock. A static WireMockExtension starts a server on a dynamic port, and @DynamicPropertySource feeds its base URL into the property the RestClient bean uses. stubFor() with okJson() answers GET /customers/42, the test calls the real client and checks the mapped result, and verify() with withHeader() and matching() confirms that the Authorization header was sent. The random port keeps tests independent so they can run in parallel.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We start WireMock on a dynamic port with the JUnit 5 WireMockExtension, register its base URL as the client's base-url property with @DynamicPropertySource so the RestClient bean calls the stub, and stub GET /customers/42 with okJson(...). After calling our client, wm.verify(getRequestedFor(urlEqualTo("/customers/42")).withHeader("Authorization", matching("Bearer .*"))) checks that the request really carried the header. The dynamic port lets several test classes run in parallel without clashing.
Why this question is asked
Almost every Spring Boot service calls other services over HTTP, and the client code is where many production bugs hide: a wrong path, a missing header, a field that does not deserialise. Mocking the client class in a unit test cannot catch those, because the HTTP request is never made. WireMock runs a real HTTP server that we program from the test, so the real client, with its real serialisation and headers, is exercised. Interviewers ask for this as a coding exercise because it combines several Spring testing pieces correctly. In this answer, we will set up the client, start WireMock, wire its address into the Spring context, write the stub and the test, verify the header, and see why the port must be dynamic.
1The Client Under Test
First, the code we want to test. A small CustomerClient wraps a RestClient, Spring's synchronous HTTP client introduced in Spring Framework 6.1. The base URL and the token come from configuration, and the client adds an Authorization header with a bearer token to every request.
Notice that the base URL is a property, not a constant. That is what makes the client testable: in production it points at the real customer service, and in the test we point it at WireMock. Using the injected RestClient.Builder matters too, because Spring Boot configures it with the application's message converters, so the test exercises the same JSON mapping as production.
2Starting WireMock and Wiring Its Address
WireMock provides a JUnit 5 extension. Declared as a static field with @RegisterExtension, it starts one WireMock server before the tests in the class and stops it afterwards. dynamicPort() asks the operating system for a free port instead of using a fixed one.
@DynamicPropertySource adds properties to the Spring environment before the application context is created. We pass a supplier, wm::baseUrl, rather than a value, so the URL is read when Spring needs the property, by which time the server is running and its port is known. The CustomerClient bean is then built with that URL, so every call it makes goes to WireMock.
There are alternatives with the same idea. The WireMock Testcontainers module runs WireMock in a container, which is useful when several services or a non-Java component must call the stub. And Spring Cloud Contract and the WireMock Spring Boot integration offer annotations that start the server and set properties for us; check your versions for the exact names.
3Stubbing the Endpoint and Calling the Client
Now the test itself. stubFor() tells WireMock how to answer a request that matches a pattern. okJson() is a shortcut for a 200 response with a Content-Type of application/json and the given body.
The call goes through the real RestClient, over a real socket, to WireMock, which returns the JSON. Jackson then maps it into the Customer record. If the path were wrong, WireMock would answer 404 because no stub matches, and the client would throw an HttpClientErrorException. If the JSON field names did not match the record, the mapping would fail. So this one test checks the path, the HTTP method, the deserialisation and the header.
4Verifying the Header
The verify() call is how we check what the client sent. WireMock records every request it receives, and verify() searches that journal for requests matching a pattern. Here we require a GET to /customers/42 whose Authorization header matches the regular expression Bearer .*. If no such request exists, verify() throws a VerificationException, and WireMock lists the closest requests it did receive, which usually makes the mistake obvious, such as a header named Authorisation or a token without the Bearer prefix.
We could make the match stricter with equalTo("Bearer test-token") to check the exact token, or use verify(1, getRequestedFor(...)) to require exactly one call, which catches a client that retries when it should not. Another way to express the same expectation is to put the header condition into the stub itself, with withHeader() on the request pattern; a request without the header then gets a 404. Verifying afterwards gives a clearer failure message, which is why it is the usual choice.
6 messages in order. Play them, or step through them one at a time.
The real client, real HTTP and real JSON mapping run against a programmable server.
5Why the Port Must Be Random
A fixed port such as 8089 works until two things want it at once. If test classes run in parallel, or two builds share a CI agent, the second WireMock server fails to start with an address already in use error, and the test fails for reasons unrelated to the code. With dynamicPort(), each server gets a free port from the operating system, and @DynamicPropertySource carries that port into the configuration, so nothing in the test depends on a particular number.
Keeping the extension static and per test class also keeps stubs isolated. Stubs registered in one test class live only in that class's server. Within a class, WireMockExtension resets stubs and the request journal between test methods by default, so each test starts with a clean server; check your version if you rely on that behaviour.
6Follow-up questions
Why not mock CustomerClient or RestClient with Mockito instead?
Mocking the client is right in a unit test of the code that uses the client, because there we care about the caller's logic. But it never sends a request, so it cannot catch a wrong path, a missing header or a JSON mapping problem. The WireMock test is the test of the client itself. Mocking RestClient's fluent API is especially painful and brittle, and it still tests nothing about HTTP.
How would you test the error case, such as a 404 from the customer service?
Stub the endpoint with willReturn(notFound()) or aResponse().withStatus(404) and assert what our client does: throw a specific exception, return an empty Optional, or whatever the contract says. A 503 stub tests retries, and withFixedDelay() tests timeouts.
How do we keep these stubs in line with the real customer service?
Hand-written stubs can drift from the real API. Contract tests, with Spring Cloud Contract or Pact, make the provider verify the same expectations, and stubs generated from those contracts or from the provider's OpenAPI description keep the consumer's tests honest.
7Conclusion
In this answer, we wrote a Spring Boot test for an HTTP client with WireMock. A static WireMockExtension starts a server on a dynamic port, and @DynamicPropertySource feeds its base URL into the property the RestClient bean uses. stubFor() with okJson() answers GET /customers/42, the test calls the real client and checks the mapped result, and verify() with withHeader() and matching() confirms that the Authorization header was sent. The random port keeps tests independent so they can run in parallel.
Open with
I'd make the client's base URL and token configuration properties, and build the RestClient from Spring's RestClient.Builder with a default Authorization header, so the test uses the real JSON setup.
Then, if they want more
In the test class I'd declare a static WireMockExtension with RegisterExtension, built with wireMockConfig dynamicPort, so it starts once for the class on a free port. Then a static DynamicPropertySource method registers customers.base-url as the supplier wm::baseUrl, plus a test token. Because it's a supplier, it's read when the context is created, after the server knows its port.
The test stubs get urlEqualTo /customers/42 to willReturn okJson with id 42 and name Ann, calls client.find(42), and asserts it gets the Customer record back. That checks the path, method and deserialisation over real HTTP. To check the header, I call wm.verify with getRequestedFor the same URL and withHeader Authorization matching Bearer dot star.
If it fails, WireMock shows the closest requests it got, which usually shows the mistake. I could tighten it to equalTo with the exact token, or verify exactly one call. The dynamic port is important: a fixed port fails when classes run in parallel or two builds share an agent. For error paths, I'd stub 404 or 503, or use withFixedDelay for timeouts.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- JUnit 5, Spring Framework 6
- 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.
- Official documentation
- JUnit user guide, Mockito documentation
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 "Write a Spring Boot test that stubs a downstream GET /customers/42 returning JSON with...": https://scrivio-interview-library.netlify.app/java/integration-testing/9cd19738c1/