WireMock: testing HTTP clients against a fake server
WireMock runs a real HTTP server inside your tests, so code that calls a REST API can be tested without the real service. This page explains how stub mappings, the request journal and near misses work, then runs real tests for success, errors and timeouts, the unmatched-request trap, retry scenarios, JSON body matching, stub priorities and network faults.
Contents
What WireMock is and how it works
Code that calls an HTTP API is hard to unit test. Calling the real service makes tests slow, flaky and dependent on its data, and it is nearly impossible to make it return a 503 or answer slowly on demand. Mocking the HTTP client object with Mockito avoids the network, but then nothing checks the URL, the headers, the JSON or the client's timeout handling, which is where most HTTP bugs are.
WireMock sits in between. It is a real HTTP server, built on Jetty, that runs inside the test JVM on a local port. The code under test talks real HTTP to it, and the test configures it through three mechanisms:
- Stub mappings: rules of the form "a request matching this method, URL, headers and body gets this response". When several match, the one with the highest priority wins, and among equal priorities the most recently added.
- The request journal: every request received is recorded, so tests can verify what the client sent, like Mockito's
but on the wire.verify - Near misses: for a request that matched nothing, WireMock finds the closest stubs and explains the differences.
Responses can be delayed, can come from stateful scenarios, or can be network faults such as a reset connection, which makes WireMock a tool for testing error handling, not just the happy path.
| Approach | Tests the real HTTP exchange? | Best for |
|---|---|---|
| Mockito mock of the client object | No | Code several layers above the HTTP call |
| WireMock in the test JVM | Yes: URL, headers, body, status, timing | Unit and integration tests of API clients |
| WireMock or the real service in Docker, via | Yes, across processes | End-to-end tests of several services |
| The real external service | Yes, but uncontrolled | Occasional contract checks, not regular tests |
WireMock 3 (2023) requires Java 11, moved to Jetty 11, and includes the WireMockExtension
The client under test
RatesClientHttpClient
import java.math.BigDecimal;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Code under test: calls an external exchange-rate API over HTTP
public class RatesClient {
private final HttpClient http = HttpClient.newHttpClient();
private final String baseUrl;
private final String apiKey;
public RatesClient(String baseUrl, String apiKey) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
}
public BigDecimal rate(String from, String to) throws Exception {
URI uri = URI.create(baseUrl + "/rates/" + from + "/" + to);
HttpRequest req = HttpRequest.newBuilder(uri)
.header("X-Api-Key", apiKey)
.timeout(Duration.ofMillis(500))
.build();
HttpResponse<String> resp;
try {
resp = http.send(req, HttpResponse.BodyHandlers.ofString());
} catch (HttpTimeoutException e) {
throw new IllegalStateException("rates service timed out", e);
}
if (resp.statusCode() == 404) {
throw new IllegalArgumentException("unknown currency pair " + from + "/" + to);
}
if (resp.statusCode() != 200) {
throw new IllegalStateException("rates service returned " + resp.statusCode());
}
Matcher m = Pattern.compile("\"rate\"\\s*:\\s*([0-9.]+)").matcher(resp.body());
if (!m.find()) {
throw new IllegalStateException("no rate in response: " + resp.body());
}
return new BigDecimal(m.group(1));
}
}
The tests
WireMockExtensionapi.baseUrl()
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
class RatesClientTest {
// A real HTTP server on a random free port, reset between tests
@RegisterExtension
static WireMockExtension api = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort()).build();
RatesClient client;
@BeforeEach
void setUp() {
client = new RatesClient(api.baseUrl(), "test-key");
}
@Test
@DisplayName("parses the rate from a 200 response")
void ok() throws Exception {
api.stubFor(get(urlEqualTo("/rates/EUR/USD"))
.withHeader("X-Api-Key", equalTo("test-key"))
.willReturn(okJson("{\"from\":\"EUR\",\"to\":\"USD\",\"rate\":1.0842}")));
assertThat(client.rate("EUR", "USD")).isEqualByComparingTo("1.0842");
api.verify(1, getRequestedFor(urlEqualTo("/rates/EUR/USD"))
.withHeader("X-Api-Key", equalTo("test-key")));
}
@Test
@DisplayName("maps 404 to IllegalArgumentException")
void notFound() {
api.stubFor(get(urlEqualTo("/rates/EUR/XYZ")).willReturn(aResponse().withStatus(404)));
assertThatThrownBy(() -> client.rate("EUR", "XYZ"))
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("EUR/XYZ");
}
@Test
@DisplayName("maps a server error to IllegalStateException")
void serverError() {
api.stubFor(get(urlEqualTo("/rates/EUR/GBP")).willReturn(aResponse().withStatus(503)));
assertThatThrownBy(() -> client.rate("EUR", "GBP"))
.hasMessage("rates service returned 503");
}
@Test
@DisplayName("gives up after the 500 ms timeout on a slow response")
void slow() {
api.stubFor(get(urlEqualTo("/rates/EUR/JPY"))
.willReturn(okJson("{\"rate\":162.3}").withFixedDelay(2000)));
long t0 = System.nanoTime();
assertThatThrownBy(() -> client.rate("EUR", "JPY")).hasMessage("rates service timed out");
assertThat((System.nanoTime() - t0) / 1000000).isLessThan(1500);
}
@Test
@DisplayName("a request no stub matches gets 404, which looks like a real 'not found'")
void unmatched() {
api.stubFor(get(urlEqualTo("/rates/EUR/CHF"))
.withHeader("X-Api-Key", equalTo("prod-key")) // client sends "test-key"
.willReturn(okJson("{\"rate\":0.94}")));
assertThatThrownBy(() -> client.rate("EUR", "CHF"))
.hasMessage("unknown currency pair EUR/CHF");
assertThat(api.findAllUnmatchedRequests()).hasSize(1);
System.out.println(" near miss: " + api.findNearMissesForAllUnmatchedRequests()
.get(0).getRequest().getHeader("X-Api-Key") + " sent, stub expects prod-key");
}
}
Output, from the launcher on the
near miss: test-key sent, stub expects prod-key
PASS a request no stub matches gets 404, which looks like a real 'not found'
PASS maps a server error to IllegalStateException
PASS parses the rate from a 200 response
PASS gives up after the 500 ms timeout on a slow response
PASS maps 404 to IllegalArgumentException
tests: 5, passed: 5, failed: 0, aborted: 0, skipped: 0
- Stubbing:
answers only requests that match the URL and the header.stubFor(get(...).withHeader(...).willReturn(okJson(...))) also sets theokJson .Content-Type - Verifying:
checks that the client sent exactly one request with the right key, much like Mockito'sapi.verify(1, getRequestedFor(...)) , but on the real HTTP request.verify - Errors: status codes 404 and 503 are one line each to simulate, which is hard to do against a real service on demand.
- Slow responses:
holds the response for 2 seconds. The client's 500 ms timeout fired and the test confirmed it gave up well before the delay ended.withFixedDelay(2000)
The unmatched-request trap
When no stub matches a request, WireMock answers 404prod-keytest-key
The test catches this by asserting that WireMock saw exactly one unmatched request, and prints the near miss: WireMock compares every unmatched request with the closest stub and reports what differed, here the header value. When a WireMock test fails unexpectedly, the near-miss report (also written to the log) is the first thing to read. Checking findAllUnmatchedRequests()@AfterEach
Scenarios, JSON bodies, priorities and faults
The second test class covers features needed for realistic clients: a service that fails once and then recovers, a POST whose JSON body must match, overlapping stubs, and a network failure. An @AfterEach
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
class AdvancedWireMockTest {
@RegisterExtension
static WireMockExtension api = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort()).build();
final HttpClient http = HttpClient.newHttpClient();
// Guard for every test: a request that matched no stub is a test bug
@AfterEach
void noUnmatchedRequests() {
assertThat(api.findAllUnmatchedRequests()).extracting(LoggedRequest::getUrl)
.as("unmatched requests").isEmpty();
}
// Retry logic under test: one retry when the service answers 503
BigDecimal rateWithRetry(RatesClient client) throws Exception {
try {
return client.rate("EUR", "USD");
} catch (IllegalStateException e) {
return client.rate("EUR", "USD");
}
}
@Test
void scenarioFirstFailsThenSucceeds() throws Exception {
api.stubFor(get(urlEqualTo("/rates/EUR/USD")).inScenario("flaky")
.whenScenarioStateIs(STARTED).willSetStateTo("recovered")
.willReturn(aResponse().withStatus(503)));
api.stubFor(get(urlEqualTo("/rates/EUR/USD")).inScenario("flaky")
.whenScenarioStateIs("recovered")
.willReturn(okJson("{\"rate\":1.09}")));
assertThat(rateWithRetry(new RatesClient(api.baseUrl(), "k")))
.isEqualByComparingTo("1.09");
api.verify(2, getRequestedFor(urlEqualTo("/rates/EUR/USD")));
}
@Test
void postBodyMatchedAsJson() throws Exception {
api.stubFor(post(urlEqualTo("/orders"))
.withRequestBody(equalToJson("{\"item\":\"pen\",\"qty\":2}", true, true))
.willReturn(aResponse().withStatus(201).withHeader("Location", "/orders/77")));
// Different key order and an extra field still match: ignoreArrayOrder, ignoreExtra
String body = "{\"qty\":2,\"item\":\"pen\",\"note\":\"gift\"}";
HttpResponse<String> resp = http.send(HttpRequest.newBuilder(
URI.create(api.baseUrl() + "/orders"))
.POST(HttpRequest.BodyPublishers.ofString(body)).build(),
HttpResponse.BodyHandlers.ofString());
assertThat(resp.statusCode()).isEqualTo(201);
assertThat(resp.headers().firstValue("Location")).contains("/orders/77");
}
@Test
void priorityPicksTheSpecificStub() throws Exception {
api.stubFor(get(urlPathMatching("/rates/.*")).atPriority(10)
.willReturn(aResponse().withStatus(404)));
api.stubFor(get(urlEqualTo("/rates/EUR/SEK")).atPriority(1)
.willReturn(okJson("{\"rate\":11.2}")));
RatesClient client = new RatesClient(api.baseUrl(), "k");
assertThat(client.rate("EUR", "SEK")).isEqualByComparingTo("11.2");
assertThatThrownBy(() -> client.rate("EUR", "ZZZ"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void connectionResetFault() {
api.stubFor(get(anyUrl()).willReturn(aResponse()
.withFault(Fault.CONNECTION_RESET_BY_PEER)));
assertThatThrownBy(() -> new RatesClient(api.baseUrl(), "k").rate("EUR", "USD"))
.isInstanceOf(IOException.class);
}
@Test
void forgottenStub() throws Exception {
api.stubFor(get(urlEqualTo("/rates/EUR/USD")).willReturn(okJson("{\"rate\":1.1}")));
new RatesClient(api.baseUrl(), "k").rate("EUR", "USD");
// a second call the test author did not stub
assertThatThrownBy(() -> new RatesClient(api.baseUrl(), "k").rate("USD", "EUR"));
}
}
Output:
PASS postBodyMatchedAsJson()
FAIL forgottenStub()
AssertionError: [unmatched requests]
Expecting empty but was: ["/rates/USD/EUR"]
PASS scenarioFirstFailsThenSucceeds()
PASS connectionResetFault()
PASS priorityPicksTheSpecificStub()
tests: 5, passed: 4, failed: 1, aborted: 0, skipped: 0
: the scenario "flaky" starts in the statescenarioFirstFailsThenSucceeds , where the stub answers 503 and moves the state to "recovered"; the next request gets the rate. The retry code returned 1.09, and the journal confirmed exactly two requests. This is how retry and circuit-breaker logic is tested deterministically.STARTED :postBodyMatchedAsJson compares the body as JSON, ignoring array order and extra fields, so a body with the keys in another order and an extra "note" still matched and got 201 with aequalToJson(json, true, true) header. A plain string comparison would have failed on whitespace or key order.Location : the catch-all stub forpriorityPicksTheSpecificStub has priority 10 and the EUR/SEK stub priority 1; lower numbers win, so SEK got 11.2 and anything else got 404./rates/.* : the server reset the connection, and the JDK client threw anconnectionResetFault .IOException lets it escape unchanged, which this test documents; a production client might wrap it like the timeout.RatesClient failed in theforgottenStub guard with the unmatched URL@AfterEach . Without the guard, the test would have passed, because it only expected some exception, and a 404 from a missing stub provides one./rates/USD/EUR
Without JUnit: a server in code, stubs as JSON, templating
The extension is a convenience. WireMockServermainmappings
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
// WireMock without JUnit: a server started in code, with a stub defined as JSON.
// The same JSON in a mappings/ directory is what standalone WireMock loads at start-up
public class StandaloneServer {
public static void main(String[] args) throws Exception {
WireMockServer server = new WireMockServer(options().dynamicPort());
server.start();
try {
server.addStubMapping(StubMapping.buildFrom("""
{
"request": { "method": "GET", "urlPathPattern": "/greet/[a-z]+" },
"response": {
"status": 200,
"body": "Hello {{request.path.[1]}}, you asked at {{request.url}}",
"transformers": ["response-template"]
}
}"""));
HttpClient http = HttpClient.newHttpClient();
for (String name : new String[] {"ana", "ben"}) {
HttpResponse<String> r = http.send(HttpRequest.newBuilder(
URI.create(server.baseUrl() + "/greet/" + name)).build(),
HttpResponse.BodyHandlers.ofString());
System.out.println(r.statusCode() + " " + r.body());
}
HttpResponse<String> miss = http.send(HttpRequest.newBuilder(
URI.create(server.baseUrl() + "/greet/ANA")).build(),
HttpResponse.BodyHandlers.ofString());
System.out.println(miss.statusCode() + " for /greet/ANA (pattern is lower case)");
System.out.println("requests in the journal: " + server.getAllServeEvents().size()
+ ", stubs: " + server.listAllStubMappings().getMappings().size());
} finally {
server.stop();
}
System.out.println("server running after stop: " + server.isRunning());
}
}
Output:
200 Hello ana, you asked at /greet/ana
200 Hello ben, you asked at /greet/ben
404 for /greet/ANA (pattern is lower case)
requests in the journal: 3, stubs: 1
server running after stop: false
- Both requests matched the pattern
, and the Handlebars expressions/greet/[a-z]+ and{{request.path.[1]}} copied the name and the URL into the response. The{{request.url}} entry turns templating on for this stub only."transformers": ["response-template"] did not match the lower-case pattern and got WireMock's default 404, the same trap as before./greet/ANA- The journal held all 3 requests, including the unmatched one, and the server held 1 stub.
shut the server down; with the JUnit extension that happens automatically after the test class.stop() - Keeping stubs as JSON files lets several teams share one fake of an API, and lets the same stubs drive a WireMock container in end-to-end tests.
Choosing features and avoiding traps
| Feature | Use |
|---|---|
| Scenarios | Stateful stubs, such as "first call returns 503, second returns 200", for testing retries |
withFixedDelay | Timeouts; keep delays short so tests stay fast |
atPriority | A catch-all stub plus specific overrides |
findAllUnmatchedRequests()@AfterEach | Catching forgotten or mismatched stubs in every test |
| Response templating | Echo parts of the request (path, headers, body) into the response |
| JSON body matching | withRequestBody(equalToJson(...))matchingJsonPath(...) |
| Faults | withFault(Fault.CONNECTION_RESET_BY_PEER) |
| Standalone mode | Run WireMock as a separate process or Docker container for manual and integration testing |
Writing stubs by hand for a large API is slow. WireMock can record instead: server.startRecording("https://api.example.com")stopRecording()
Use dynamicPort()static