How-to › Test and mock integrations

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.

Audience
API consumer
Level
intermediate
Topic
Mock an API
Languages
Java
Verified

Your service posts quote requests to an upstream rates API, so its tests either reach a shared sandbox or mock the HTTP client object. The sandbox fails the build whenever it is down. The mocked object never sees the bytes the service sends, so a weight sent in kilograms where the API wants grams passes every test and ships.

What you get

You will end up with a JUnit 5 suite that runs WireMock on a free port per test class, stubs the upstream, and checks both the parsed answer and the exact request. This is for you if your Java service calls HTTP APIs it does not own.

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

ApproachWhen it fitsWhat it costs youWhen to pick something else
HoverflyA real service exists, and you want its traffic captured once and replayedA native binary run as a proxy, so your client must honor the JVM proxy settingsYour client sets its own proxy, or there is no service to capture yet
MockServerThe same process should also proxy real traffic or show received requests in a dashboardA 102 MB jar without dependencies, plus an expectation DSL of its own to learnTests need stubs and verification only, and download size matters in CI
WireMockJUnit tests that write their stubs in code and verify what was sentA 19.5 MB standalone jar, and stubs that drift unless something checks them against the APIYou 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 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, 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().

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, 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 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.

java -cp "classes:jars/*" example.VerifyDemo
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 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.

java -cp "classes:jars/*" example.RunTests
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 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().

  // 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"))
java -cp "classes:jars/*" example.PortClash
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.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.

      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));
cat records/mockserver.txt
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 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.

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.

Footnotes

  1. The text is the operating system’s, not WireMock’s or Jetty’s. The errno manual page 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. ↩︎ Back to text

  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 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. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.