# How to stub HTTP dependencies in Java tests with WireMock

> Run WireMock as a JUnit 5 extension on a dynamic port, stub the upstream calls your service makes, and verify the requests it sent as well as its answers.

Source: https://voxgig.com/howto/stub-http-dependencies-in-java-tests

- Audience: api-consumer
- Level: intermediate
- Languages: java
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Register `WireMockExtension` with `wireMockConfig().dynamicPort()`, point your service's client at `baseUrl()`, and stub each upstream call with `stubFor`. Assert on what the service returns, then call `verify` with `equalToJson` on the body, because a stub that matches on the URL answers a wrong payload too. A fixed port shared by test classes running in parallel fails one class with `Address already in use`.

---
## You will need

Java 21 and JUnit 5. The sample runs without Maven or Gradle: `npm ci` in its directory downloads
`wiremock-standalone` and the JUnit Platform console launcher from Maven Central, checks their
SHA-256 hashes, and compiles the sources with `javac`. Verified 2026-11-30 against OpenJDK
21.0.13.1, WireMock 3.13.2, JUnit 5.14.5 and MockServer 9.4.0.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Hoverfly](https://docs.hoverfly.io/projects/hoverfly-java/en/latest/index.html) | A real service exists, and you want its traffic captured once and replayed | A native binary run as a proxy, so your client must honor the JVM proxy settings | Your client sets its own proxy, or there is no service to capture yet |
| [MockServer](https://www.mock-server.com/mock_server/running_mock_server.html) | The same process should also proxy real traffic or show received requests in a dashboard | A 102 MB jar without dependencies, plus an expectation DSL of its own to learn | Tests need stubs and verification only, and download size matters in CI |
| [WireMock](https://wiremock.org/docs/junit-jupiter/) | JUnit tests that write their stubs in code and verify what was sent | A 19.5 MB standalone jar, and stubs that drift unless something checks them against the API | You want fixtures recorded from real traffic rather than written by hand |

Hoverfly reverses the order of work: it records a real exchange in
[capture mode](https://docs.hoverfly.io/en/latest/pages/keyconcepts/modes/capture.html) and
replays it. That saves writing stubs, but it needs a live service first and a client that honors
the JVM proxy. MockServer covers the same stub-and-verify loop as WireMock, as the record below
shows, and adds a forwarding proxy and a
[dashboard](https://www.mock-server.com/mock_server/mockserver_ui.html), at about five times the
download.

## Start WireMock on a port of its own

The extension starts one server before the class's first test and stops it after the last. Ask
for a dynamic port, bind it to loopback, and build the client from `baseUrl()`.

```java title="src/example/ShippingRatesTest.java"
class ShippingRatesTest {
  @RegisterExtension
  static WireMockExtension rates = WireMockExtension.newInstance()
      .options(wireMockConfig().dynamicPort().bindAddress("127.0.0.1"))
      .build();

  // The stub runs on 127.0.0.1, so the client never goes through a proxy.
  private ShippingRates client() {
    HttpClient http = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build();
    return new ShippingRates(http, URI.create(rates.baseUrl() + "/"), "demo_key_123");
  }

  @Test
  void returnsTheQuoteAndSendsTheDocumentedRequest() throws Exception {
    rates.stubFor(post(urlEqualTo("/v1/rates"))
        .willReturn(okJson("{\"amountCents\":1250,\"currency\":\"EUR\"}")));

    assertEquals(new ShippingRates.Quote(1250, "EUR"), client().quote("D02 X285", "BT1 5GS", 1200));

    rates.verify(1, postRequestedFor(urlEqualTo("/v1/rates"))
        .withHeader("Authorization", equalTo("Bearer demo_key_123"))
        .withHeader("Content-Type", equalTo("application/json"))
        .withRequestBody(equalToJson("{\"from\":\"D02 X285\",\"to\":\"BT1 5GS\",\"weightGrams\":1200}")));
  }
```

`NO_PROXY` keeps the test's traffic independent of the machine's proxy settings. A
`java.net.http.HttpClient` built without a proxy selector
[uses the default one](https://docs.oracle.com/en/java/javase/21/docs/api/java.net.http/java/net/http/HttpClient.Builder.html),
which reads the proxy properties of the JVM. The service takes the client and the base URL as
arguments, so production code passes its own.

The test has two halves. `assertEquals` covers the response handling. `verify` covers the
request: one call, the bearer token, the `Content-Type` header, and a body that
[`equalToJson`](https://wiremock.org/docs/request-matching/) compares as JSON, so key order and
whitespace do not matter.

## Verify what the service sent

A stub that matches on the URL alone answers any body. `VerifyDemo` makes the mistake from the
opening, passing 1 where 1,200 grams were meant, against the same stub.

```bash
java -cp "classes:jars/*" example.VerifyDemo
```

```text output
quote returned: Quote[amountCents=1250, currency=EUR]
verify threw VerificationException:
No requests exactly matched. Most similar request was:  expected:<
POST
/v1/rates

[equalToJson]
{
  "from" : "D02 X285",
  "to" : "BT1 5GS",
  "weightGrams" : 1200
}> but was:<
POST
/v1/rates


{
  "from" : "D02 X285",
  "to" : "BT1 5GS",
  "weightGrams" : 1
}>
```

The service got its quote and returned it. Only the [verification](https://wiremock.org/docs/verifying/)
noticed, and its message prints the closest request it received beside the one it expected.

## Check it worked

`RunTests` runs the suite through the JUnit Platform launcher, prints one line per test, and
exits 1 on any failure or when no test ran.

```bash
java -cp "classes:jars/*" example.RunTests
```

```text output
PortClashTest > dynamicPortsLetBothClassesPass: SUCCESSFUL
PortClashTest > oneFixedPortFailsOneOfTwoParallelClasses: SUCCESSFUL
RenamedFieldTest > renamingTheBodyFieldFailsOnlyTheTestThatVerifiesTheBody: SUCCESSFUL
ShippingRatesTest > a503BecomesUpstreamUnavailableAfterOneAttempt: SUCCESSFUL
ShippingRatesTest > aBadPostcodeNeverReachesTheUpstream: SUCCESSFUL
ShippingRatesTest > aStubbedBodyWithoutAPriceIsRefused: SUCCESSFUL
ShippingRatesTest > returnsTheQuoteAndSendsTheDocumentedRequest: SUCCESSFUL
VerifyDemoTest > theStubAnswersTheWrongPayloadAndVerifyCatchesIt: SUCCESSFUL
8 tests, 0 failed
```

The line to look for is `8 tests, 0 failed`. `RenamedFieldTest` renames the body field from
`weightGrams` to `weight` in a copy of `ShippingRates`, runs `ShippingRatesTest` against it in a
second JVM, and requires exactly one failure: the test that calls `verify`, failing in `verify`.
Every test of the parsed response still passes on that build.

## When it goes wrong

A test class fails before its first test, on some runs only, with a startup error. Two classes asked
for the same fixed port while JUnit's
[parallel execution](https://docs.junit.org/5.14.5/writing-tests/parallel-execution.html) ran
them at once. `PortClash` runs two copies of a test class at the same time, first with one fixed
port written into both, then with `dynamicPort()`.

```java title="src/example/FixedPortFirstTest.java"
  // A port written into the test: every class that copies this line asks for the same one.
  @RegisterExtension
  @Order(2)
  static WireMockExtension rates = WireMockExtension.newInstance()
      .options(wireMockConfig().port(Integer.getInteger("demo.fixed.port", 8089)).bindAddress("127.0.0.1"))
```

```bash
java -cp "classes:jars/*" example.PortClash
```

```text output
one fixed port, two classes in parallel
  tests passed: 1 of 2
  class failed: FAILED: FatalStartupException, caused by BindException: Address already in use
dynamicPort(), two classes in parallel
  tests passed: 2 of 2
```

The losing class depends on the scheduler, so the run reports how many passed rather than which.
The error names a socket, not a test, which is why it reads like a network fault.[^1] Ask for
`dynamicPort()` and read the port back from the extension, and each server gets
[a port of its own](https://docs.kernel.org/networking/ip-sysctl.html).[^2] The declarative
`@WireMockTest` annotation defaults to a random port and takes `httpPort` only when you pass one.

## Run MockServer against the same service

`record.sh` ran MockServer 9.4.0 once against the same `ShippingRates` class, with its logging and
dashboard analytics off, and committed what the program printed.

```java title="record/MockServerRun.java"
      System.out.println("quote returned: " + client.quote("D02 X285", "BT1 5GS", 1200));
      mock.verify(request().withMethod("POST").withPath("/v1/rates")
              .withHeader("Authorization", "Bearer demo_key_123")
              .withBody(json("{\"from\":\"D02 X285\",\"to\":\"BT1 5GS\",\"weightGrams\":1200}")),
          VerificationTimes.exactly(1));
```

```bash
cat records/mockserver.txt
```

```text output
quote returned: Quote[amountCents=1250, currency=EUR]
verify exactly(1) with the documented body: passed
verify with weightGrams 1: AssertionError: Request not found exactly once, expected:<{
```

The two tools agree on the outcome. MockServer's
[verification](https://www.mock-server.com/mock_server/verification.html) throws an
`AssertionError` where WireMock throws its own `VerificationException`.

## When not to do this

Do not stub an upstream you also own and deploy together with the caller. A stub returns what
you wrote, so a renamed field on the provider side passes here; a contract test against the
provider catches it.

Do not hand-write stubs for an API that changes weekly. Each stub is a copy of someone else's
behavior, and a copy needs a check. Hoverfly's capture mode records fresh fixtures from the real
service, and MockServer can sit in front of it as a proxy.

Skip WireMock when the code under test takes an interface you can fake in memory.
A fake object costs no port, no jar and no server start-up, and the wire format may not be the
thing under test.

## Related how-tos

- [Stub outbound HTTP calls in Node tests with nock](/howto/stub-outbound-node-http-calls-with-nock)

- [Choose between a network mock and an in-process mock](/howto/choose-between-network-and-in-process-mocks)

- [Control which stub wins when mock rules overlap](/howto/control-which-stub-wins-when-rules-overlap)

- [Inject latency and failures into SDK tests](/howto/inject-latency-and-failures-into-sdk-tests)

- [Intercept fetch calls in browser tests with MSW](/howto/intercept-fetch-in-browser-tests-with-msw)

## Last verified

Verified 2026-11-30 against OpenJDK 21.0.13.1, WireMock 3.13.2 and JUnit 5.14.5, with
MockServer 9.4.0 run once in `record.sh`. Every output block is what the command before it
printed. Hoverfly
was not run. Hoverfly Java 0.20.2 lists seven runtime dependencies for a build tool to resolve and
starts a native Hoverfly process, and this sample uses neither. Its row comes from its documentation.

[^1]: The text is the operating system's, not WireMock's or Jetty's. The
[`errno` manual page](https://man7.org/linux/man-pages/man3/errno.3.html) gives `EADDRINUSE` the
words "Address already in use" and marks the name as POSIX.1-2001. WireMock reports the failure
as a `FatalStartupException`, and `PortClash` prints the root cause beside it, because only the
root cause says what happened.

[^2]: A server that asks for port 0 is given one from the range in `ip_local_port_range`, which the
[kernel's IP `sysctl` documentation](https://docs.kernel.org/networking/ip-sysctl.html) sets at
32768 to 60999 by default. The same page advises that the two numbers have different parity,
one even and one odd, and the defaults follow its advice.