Skip to content
javahacks.dev
Testing

How to Test With WireMock and Mock External HTTP APIs

Mock HTTP dependencies with WireMock in JUnit: stubbing responses, verifying requests, simulating delays and faults, scenarios and Spring integration.

6 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the Spring, Selenium, JUnit5 and Jenkins logos.

A service that calls someone else's HTTP API is hard to test honestly. Mocking the client class proves that your code calls a method, not that it sends the right request or survives a slow, broken or surprising reply. WireMock fixes that by running a real HTTP server inside the test. The client is configured to talk to it, so the real serialisation, headers, timeouts and error handling are all exercised, and the test says exactly what the "remote service" returns. This post sets up WireMock with JUnit 5, shows request matching and failure simulation, covers retries with scenarios, wires it into Spring Boot and discusses where it misleads. It uses WireMock 3, JUnit 5 and JDK 25.

Setup

pom.xmlXML
<dependency>
  <groupId>org.wiremock</groupId>
  <artifactId>wiremock</artifactId>
  <version>3.9.2</version>
  <scope>test</scope>
</dependency>

For a standalone JVM test, the JUnit extension manages the server's lifecycle on a random port:

src/test/java/com/example/rates/RateClientTest.javajava
class RateClientTest {

    @RegisterExtension
    static WireMockExtension wm = WireMockExtension.newInstance()
        .options(wireMockConfig().dynamicPort())
        .build();

    RateClient client = new RateClient(wm.baseUrl());
}

dynamicPort() avoids port clashes between test classes and parallel builds. wm.baseUrl() is the address to hand to the client. A static extension starts one server for the class and resets stubs between tests; an instance field would start one per test.

A test

java
@Test
void converts_using_the_published_rate() {
    wm.stubFor(get(urlPathEqualTo("/rates/EUR"))
        .withQueryParam("to", equalTo("GBP"))
        .withHeader("Authorization", equalTo("Bearer test-token"))
        .willReturn(okJson("""
            {"base":"EUR","to":"GBP","rate":0.8412}
            """)));

    BigDecimal result = client.convert(new BigDecimal("100"), "EUR", "GBP");

    assertEquals(0, new BigDecimal("84.12").compareTo(result));
    wm.verify(1, getRequestedFor(urlPathEqualTo("/rates/EUR")));
}

stubFor registers a mapping: when a request matches, return this response. If the client sends a different path, query or header, WireMock answers 404 with a diff that shows what was expected and what arrived, and that message is usually all you need to see which part of the request was wrong. verify asserts afterwards that the request was made the expected number of times. Together they cover both directions: the client sends the right thing, and handles the reply.

Matching requests

Matching is where the power and the discipline are. Match the parts of the request that matter to the contract and nothing else:

java
stubFor(post(urlEqualTo("/payments"))
    .withHeader("Content-Type", containing("application/json"))
    .withRequestBody(matchingJsonPath("$.amount", equalTo("19.90")))
    .withRequestBody(matchingJsonPath("$.currency", equalTo("EUR")))
    .willReturn(aResponse().withStatus(201).withHeader("Location", "/payments/p-1")));

urlEqualTo matches the path and query exactly, urlPathEqualTo only the path, urlPathMatching a regular expression. JSON bodies are best matched with matchingJsonPath or equalToJson(..., ignoreExtraElements = true) so that adding an unrelated field to the request does not break every test. A stub that matches the whole body byte for byte turns every formatting change into a failure. The matcher reference is in the stubbing documentation.

Priorities and specificity matter when several stubs could match: the most recently added stub wins by default, and atPriority(n) sets an explicit order, which lets you declare a catch-all 500 at low priority and specific successes above it.

Failure behaviour

The reason to use a real server is the behaviour you cannot get from a mock object: slow responses, broken connections and bad data.

java
stubFor(get("/rates/EUR").willReturn(aResponse().withFixedDelay(3000).withStatus(200)));
stubFor(get("/rates/USD").willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));
stubFor(get("/rates/JPY").willReturn(aResponse().withStatus(503).withBody("maintenance")));
stubFor(get("/rates/CHF").willReturn(ok("this is not json")));

The delay tests your read timeout: set the client's timeout to one second and assert that the call fails within about a second, not three. Faults such as CONNECTION_RESET_BY_PEER, EMPTY_RESPONSE and MALFORMED_RESPONSE_CHUNK simulate what a flaky network does. A 503 checks the error path, and invalid JSON checks that parse errors become a sensible exception and not a stack trace in the response. Timeouts are a frequent production issue, and the client settings are discussed in network timeout issues.

Retries with scenarios

A retry policy needs a server that fails and then succeeds. Scenarios give WireMock state:

java
stubFor(get("/rates/EUR").inScenario("flaky")
    .whenScenarioStateIs(Scenario.STARTED)
    .willReturn(aResponse().withStatus(503))
    .willSetStateTo("second try"));

stubFor(get("/rates/EUR").inScenario("flaky")
    .whenScenarioStateIs("second try")
    .willReturn(okJson("{\"rate\":0.84}")));

client.convert(BigDecimal.TEN, "EUR", "GBP");

wm.verify(2, getRequestedFor(urlPathEqualTo("/rates/EUR")));

The first call gets a 503 and moves the scenario forward, the second succeeds, and the verification confirms that exactly two requests were made. Use it to check backoff, the maximum attempts and that a non-idempotent call is not retried. The patterns are in retries, timeouts and bulkheads.

With Spring Boot

java
@SpringBootTest
@WireMockTest(httpPort = 0)
class RateServiceIT {

    @DynamicPropertySource
    static void rates(DynamicPropertyRegistry registry) {
        registry.add("rates.base-url", () -> "http://localhost:" + wmPort);
    }
}

The simplest wiring is a property for the remote base URL, overridden in the test with the server's address through @DynamicPropertySource. The application's own RestClient or WebClient bean is then the real one, pointed at WireMock. Put the base URL in configuration from the start; a hard-coded URL cannot be tested this way. Spring Cloud Contract's stub runner uses WireMock underneath, as described in Spring Cloud Contract, and testing a service among others without starting them all is covered in testing microservices without running everything.

Record and playback

WireMock can proxy requests to the real API and record the responses as stub files, which you then commit and replay. It is a quick way to build stubs for a verbose API. Review recordings before committing: they contain real data, tokens and sometimes personal information. Strip secrets, and trim the stubs to what the tests need. Recorded stubs also age, so a refresh process is needed.

The honesty problem

A stub encodes what you believe the API does. If your belief is wrong, the test passes and production fails. The API may change, or you may have misread the documentation, and WireMock cannot tell. Three habits reduce the gap: build stubs from the provider's published examples or OpenAPI description, as in contract-first development; refresh recordings against the real service on a schedule; and add a small number of tests against the real sandbox, tagged so they run less often. For services you control, contract tests are stronger than stubs because the provider verifies them.

Organising stubs

Inline stubs are fine for a few tests. When many tests share the same remote API, move the stubs into a helper class with one method per scenario, named for the behaviour: ratesAvailable(), ratesDown(), ratesSlow(). A test then reads as a sentence, and a change to the API's shape is fixed in one place. WireMock also loads mapping files from src/test/resources/mappings and body files from __files, which suits large JSON responses that are unwieldy as Java text blocks. Keep the files small and named for the case, and review them like code, since a stale stub is a lie that the test suite believes.

Reset state between tests. The extension resets stubs and the request journal after each test by default, which is what you want; if you register stubs in a @BeforeAll, use a different reset policy deliberately. A test that passes only because an earlier test left a stub behind is a test waiting to break when the order changes.

Checking what the client sent

verify with a request pattern is the way to assert on outgoing requests: headers, query, and body. For a body check, equalToJson with ignoreExtraElements keeps the assertion about the fields that matter. When a verification fails, WireMock prints the closest request it saw, with a diff, which usually shows the cause at once, such as a missing Content-Type or a query parameter in the wrong case. Look at the unmatched requests with findAllUnmatchedRequests() at the end of a test to catch calls you did not stub, which would otherwise show as 404 responses deep inside the client's error handling.

Where this does not apply

For code that calls a database, use a real database in a container, not WireMock. For gRPC or messaging, use tooling for those protocols; WireMock speaks HTTP, with gRPC support through an extension. The reference is the WireMock documentation.

Also inSpring MVC
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.