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.

Share

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 verify but on the wire.
  • 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.

Ways to test HTTP client code
ApproachTests the real HTTP exchange?Best for
Mockito mock of the client objectNoCode several layers above the HTTP call
WireMock in the test JVMYes: URL, headers, body, status, timingUnit and integration tests of API clients
WireMock or the real service in Docker, via TestcontainersYes, across processesEnd-to-end tests of several services
The real external serviceYes, but uncontrolledOccasional contract checks, not regular tests

WireMock 3 (2023) requires Java 11, moved to Jetty 11, and includes the WireMockExtension for JUnit 5. The tests below use WireMock 3.9.1 (the standalone JAR) with JUnit 5.12 and AssertJ on JDK 21.

The client under test

RatesClient fetches an exchange rate from a REST API with the JDK's HttpClient. It sends an API key header, waits at most 500 ms, maps 404 and other errors to exceptions, and pulls the rate out of the JSON response. All of those behaviors need an HTTP server to test.

Java
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

WireMockExtension starts a server on a free port before the tests and resets its stubs between them. Each test points the client at api.baseUrl(), defines how the server should answer, and checks what the client does.

Java
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 JUnit 5 page:

Output
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: stubFor(get(...).withHeader(...).willReturn(okJson(...))) answers only requests that match the URL and the header. okJson also sets the Content-Type.
  • Verifying: api.verify(1, getRequestedFor(...)) checks that the client sent exactly one request with the right key, much like Mockito's verify, but on the real HTTP request.
  • 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: withFixedDelay(2000) 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.

The unmatched-request trap

When no stub matches a request, WireMock answers 404. In the last test, the stub expected the API key prod-key, but the client sent test-key. The client therefore received a 404, which it reasonably interpreted as "unknown currency pair". A test that only checked for an exception would have passed for the wrong reason.

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() is empty in an @AfterEach method guards against the trap in every test.

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 method fails any test that left an unmatched request behind, and the last test forgets a stub on purpose to show that guard working.

Java
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:

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
  • scenarioFirstFailsThenSucceeds: the scenario "flaky" starts in the state STARTED, 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.
  • postBodyMatchedAsJson: equalToJson(json, true, true) 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 a Location header. A plain string comparison would have failed on whitespace or key order.
  • priorityPicksTheSpecificStub: the catch-all stub for /rates/.* has priority 10 and the EUR/SEK stub priority 1; lower numbers win, so SEK got 11.2 and anything else got 404.
  • connectionResetFault: the server reset the connection, and the JDK client threw an IOException. RatesClient lets it escape unchanged, which this test documents; a production client might wrap it like the timeout.
  • forgottenStub failed in the @AfterEach guard with the unmatched URL /rates/USD/EUR. Without the guard, the test would have passed, because it only expected some exception, and a 404 from a missing stub provides one.

Without JUnit: a server in code, stubs as JSON, templating

The extension is a convenience. WireMockServer can be started from any code, which is useful in a main method for manual testing, in other test frameworks or in a Spring test context. Stubs can also be written as JSON instead of Java: the same documents, placed in a mappings directory, are what the standalone JAR and the WireMock Docker image load at start-up. The stub below uses a path pattern and response templating, so one stub greets any lower-case name.

Java
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:

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 /greet/[a-z]+, and the Handlebars expressions {{request.path.[1]}} and {{request.url}} copied the name and the URL into the response. The "transformers": ["response-template"] entry turns templating on for this stub only.
  • /greet/ANA did not match the lower-case pattern and got WireMock's default 404, the same trap as before.
  • The journal held all 3 requests, including the unmatched one, and the server held 1 stub. stop() shut the server down; with the JUnit extension that happens automatically after the test class.
  • 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

Which WireMock feature to use
FeatureUse
ScenariosStateful stubs, such as "first call returns 503, second returns 200", for testing retries
withFixedDelayTimeouts; keep delays short so tests stay fast
atPriorityA catch-all stub plus specific overrides
findAllUnmatchedRequests() in @AfterEachCatching forgotten or mismatched stubs in every test
Response templatingEcho parts of the request (path, headers, body) into the response
JSON body matchingwithRequestBody(equalToJson(...)) or matchingJsonPath(...) for POST requests
FaultswithFault(Fault.CONNECTION_RESET_BY_PEER) to simulate network failures
Standalone modeRun 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") makes it act as a proxy to the real service, and stopRecording() turns the exchanges it saw into stub mappings that can be saved as JSON and replayed in every later test run. Review recorded stubs before committing them, because they contain whatever the real service returned, including tokens and personal data.

Use dynamicPort() rather than a fixed port so parallel builds do not collide, and a static extension field so one server serves the whole class; the extension resets stubs and the journal between tests. For testing against a real database or message broker rather than a fake, see Testcontainers. For mocking plain Java collaborators, see Mockito.