Post

Stub a Dependency With WireMock in REST Assured Tests

Test an API whose third-party dependency you don't control, with REST Assured calling your API and WireMock playing the provider it calls, covering WireMockExtension, request patterns, a stubbed rate, half-even rounding, unmatched requests and input that never reaches the provider.

Stub a Dependency With WireMock in REST Assured Tests

The quote service converts an amount with today’s exchange rate, which it gets from an external FX provider. In a test, the real provider is a problem: it costs money per call, its rates change every minute, it’s down for maintenance on Sunday, and it will never return the exact rate that tests a rounding edge case. You need a stand-in that answers whatever the test needs, and checks that your service asked properly. In this guide, you’ll let WireMock play the provider, while REST Assured tests your service as usual.

Level: Advanced · Time: 25 minutes · Part of: Module 10: Stubbing Dependencies with WireMock, section 1

What You’ll Build

You’ll build a test class called StubbingBasicsTest with five tests. Two stub the provider’s rate and check the quote, one shows a request that matches no stub, one calls the stub directly with REST Assured, and one proves invalid input never reaches the provider.

Each tool has its own side:

1
test --REST Assured--> QuoteService --HttpClient--> WireMock (the FX provider)

When you’re done, Maven reports five passing tests:

1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Stub the provider’s answers.
  • Find out what didn’t match.
  • Prove the provider wasn’t called.

What You Need

  • About 25 minutes
  • JDK 26 or later
  • Maven 3.9 or later
  • An IDE (IntelliJ IDEA, VS Code or Eclipse)
  • Knowledge: you can send a JSON body and check a response, as taught throughout the earlier modules, and you know why money is compared as text, from Check Money Exactly With BigDecimal in REST Assured. No WireMock experience is needed.

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: this is the first section of Module 10, so you start from scratch. Create StubbingBasicsTest in the module-10 test sources and follow every heading below.
  • Skip ahead: open the finished class (StubbingBasicsTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: clone the examples repository and change into it:

1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples

If you’ve already cloned it for an earlier module, run git pull instead. The module uses WireMock 3.13, which runs inside the test’s JVM, so there’s nothing to install or start.

Out of scope: this guide doesn’t cover faults, delays, verifying calls in depth, or response templates; they’re taught in section 2 and the sections after it.

Understand Stubbing a Dependency

The problem. Your API calls a third party. Against the real one, tests are slow, cost money, depend on today’s data, and can’t reach edge cases on demand. And a test can’t see what your API sent to the third party, so it can’t tell whether your API asked correctly.

The concept. WireMock is an HTTP server for tests. Instead of running real logic, it answers with what you told it to, a stub:

  • A request pattern says which requests the stub matches: method, path, query parameters, headers, body.
  • A response says what to answer: status, headers and body.

REST Assured tests your API. WireMock plays the provider your API calls. The service is configured with WireMock’s URL instead of the real provider’s.

When to use each. Stub every dependency your API calls over HTTP, and make the request patterns as strict as the provider: a strict stub fails the test when your API sends the wrong request. Keep the provider’s patterns in one place, and choose the response per test.

Let the stub demand what the real provider demands, and answer what the test needs.

Meet the API Under Test

QuoteService answers POST /api/v1/quotes:

1
{"sourceCurrency": "EUR", "targetCurrency": "GBP", "sourceAmount": "100.00"}

To answer, it asks the FX provider for the rate:

1
2
3
4
GET /v2/rates?base=EUR&symbols=GBP HTTP/1.1
Authorization: Bearer fx-api-key
X-Client-Id: payments-service
Accept: application/json

The provider answers {"base": "EUR", "timestamp": 1767225600, "rates": {"GBP": 0.8523}}, and the service returns a quote, with the target amount rounded half-even to two decimals:

1
2
{"quoteId":"q-84484afb","sourceCurrency":"EUR","targetCurrency":"GBP","sourceAmount":"100.00",
 "rate":"0.8523","targetAmount":"85.23","expiresAt":"2026-11-22T07:53:10.881028Z"}

Two answers are 422, with different details:

Causeerrors[0].detail
Invalid input, checked before the provider is calledneeds two different ISO 4217 currencies and a positive amount with two decimals
The provider answers 404the FX provider doesn't support EUR/GBP

Your tests check these values:

  • rate and targetAmount in the quote, as strings.
  • The status and the errors of a refused quote.
  • Which requests reached the provider.

Stub the Provider’s Answers

Meet FxProviderStubs

Goal: see where the provider’s contract lives, so the tests don’t repeat it.

The module’s support package already contains FxProviderStubs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/** {@code GET /v2/rates?base=..&symbols=..} with the headers the quote service must send. */
public static MappingBuilder ratesRequest(String base, String symbol) {
    return WireMock.get(WireMock.urlPathEqualTo("/v2/rates"))
        .withQueryParam("base", WireMock.equalTo(base))
        .withQueryParam("symbols", WireMock.equalTo(symbol))
        .withHeader("Authorization", WireMock.equalTo("Bearer " + QuoteService.API_KEY))
        .withHeader("X-Client-Id", WireMock.equalTo(QuoteService.CLIENT_ID));
}

/** The provider's normal answer for one rate. */
public static String ratesBody(String base, String symbol, String rate) {
    return """
        {"base": "%s", "timestamp": 1767225600, "rates": {"%s": %s}}
        """.formatted(base, symbol, rate);
}

/** A quote request for our own API. */
public static String quoteRequest(String source, String target, String amount) {
    return """
        {"sourceCurrency": "%s", "targetCurrency": "%s", "sourceAmount": "%s"}
        """.formatted(source, target, amount);
}

What’s happening:

  • ratesRequest(..) is a strict request pattern: the path, both query parameters and both headers must match. A stub built from it answers only when the service calls the provider correctly.
  • ratesBody(..) builds the provider’s answer for one rate, and quoteRequest(..) the body for your own API.
  • WireMock’s methods are called through the WireMock class, such as WireMock.get(..) and WireMock.equalTo(..).

Checkpoint: open FxProviderStubs.java in your IDE. It compiles as it is.

Don’t statically import WireMock’s equalTo(..) next to Hamcrest’s. With both imported, a REST Assured check such as body("a", equalTo("b")) picks WireMock’s, and fails to compile with no suitable method found for body(java.lang.String,com.github.tomakehurst...). Call WireMock’s methods through the class.

Set Up the Test Class

Goal: start WireMock and the quote service, with the service calling WireMock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.javanibble.module_10.section_01;

import static com.javanibble.module_10.support.FxProviderStubs.quoteRequest;
import static com.javanibble.module_10.support.FxProviderStubs.ratesBody;
import static com.javanibble.module_10.support.FxProviderStubs.ratesRequest;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import com.javanibble.fx.QuoteService;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;

import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

class StubbingBasicsTest {

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

    private static QuoteService service;

    @BeforeAll
    static void startService() {
        service = QuoteService.start(fxProvider.baseUrl());          // the service calls WireMock, not the internet
    }

    @AfterAll
    static void stopService() {
        service.close();
    }

    private static RequestSpecification quotes() {
        return given().baseUri(service.baseUri()).port(service.port()).basePath("/api/v1").contentType(ContentType.JSON);
    }
}

What’s happening:

  • WireMockExtension starts WireMock before the class and stops it after. dynamicPort() picks a free port, such as http://localhost:60745.
  • fxProvider.baseUrl() is WireMock’s address, which the service uses as the provider’s. Make a dependency’s base URL configurable, so a test can do this.
  • The extension removes all stubs after each test: at the start of the next test, there were none, so no stub leaks from one test into another.
  • quotes() points REST Assured at your service, not at WireMock.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Use the Provider’s Rate

Goal: stub a rate, and check the quote your service builds from it.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aQuoteUsesTheProvidersRate() {
    fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.8523"))));

    quotes()
        .body(quoteRequest("EUR", "GBP", "100.00"))
    .when()
        .post("/quotes")
    .then()
        .statusCode(201)
        .body("rate", equalTo("0.8523"))
        .body("targetAmount", equalTo("85.23"));
}

What’s happening:

  • stubFor(..) registers the stub, and okJson(..) answers 200 with a JSON body.
  • The test then uses REST Assured as usual, against your service, which calls WireMock for the rate.
  • The rate is fixed, so the target amount is predictable: 100.00 × 0.8523 = 85.23.

Checkpoint: run StubbingBasicsTest from your IDE. One test runs and passes.

Reach a Rounding Tie

Goal: use a stubbed rate that hits exact rounding ties, which a real provider never would on demand.

Add this test to the class:

1
2
3
4
5
6
7
8
9
@Test
void roundingIsHalfEven() {
    // With a rate of 0.5, 10.05 gives 5.025 and 10.15 gives 5.075: exact ties. Half-even ("banker's rounding")
    // rounds a tie to the even neighbour, so 5.02 and 5.08. A stub makes such edge cases easy to reach.
    fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.5"))));

    quotes().body(quoteRequest("EUR", "GBP", "10.05")).when().post("/quotes").then().body("targetAmount", equalTo("5.02"));
    quotes().body(quoteRequest("EUR", "GBP", "10.15")).when().post("/quotes").then().body("targetAmount", equalTo("5.08"));
}

What’s happening:

  • With a rate of 0.5, 10.05 gives 5.025 and 10.15 gives 5.075: exact ties.
  • Half-even rounding, also called banker’s rounding, rounds a tie to the even neighbour: 5.02 and 5.08.
  • Half-up rounding would give 5.03 and 5.08, so the first quote tells the two apart. One stub serves both requests in the test.

Checkpoint: run the class again. Two tests pass.

Find Out What Didn’t Match

See an Unmatched Request

Goal: show what happens when the service’s request doesn’t match the stub.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void aRequestWithoutTheRightHeadersMatchesNoStub() {
    // This stub demands a different API key, so the service's request doesn't match it, WireMock answers 404,
    // and the service reports an unsupported currency. The stub is part of the test's specification.
    fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates"))
        .withHeader("Authorization", WireMock.equalTo("Bearer another-key"))
        .willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));

    quotes().body(quoteRequest("EUR", "GBP", "100.00")).when().post("/quotes").then().statusCode(422);
}

What’s happening:

  • The stub demands another API key, so the service’s request doesn’t match it.
  • WireMock answers 404 to any request no stub matches, and the service turns that into 422 with the FX provider doesn't support EUR/GBP.
  • A strict stub is part of the test’s specification: it fails the test when the service sends the wrong headers.

Checkpoint: run the class again. Three tests pass.

A missing or wrong stub looks to your service like a real 404 from the provider, so the test fails with a misleading message, and WireMock prints nothing to the console. When a test fails in a surprising way, check whether the stub matched, for example by calling it directly, as in the next step.

Call the Stub Directly

Goal: see exactly what a stub answers, while you write it.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void restAssuredCanCallTheStubDirectly() {
    // Handy while writing a stub: see exactly what it answers.
    fxProvider.stubFor(ratesRequest("EUR", "USD").willReturn(WireMock.okJson(ratesBody("EUR", "USD", "1.09"))));

    given()
        .baseUri(fxProvider.baseUrl())
        .header("Authorization", "Bearer " + QuoteService.API_KEY)
        .header("X-Client-Id", QuoteService.CLIENT_ID)
        .queryParam("base", "EUR")
        .queryParam("symbols", "USD")
    .when()
        .get("/v2/rates")
    .then()
        .statusCode(200)
        .body("rates.USD", equalTo(1.09f));
}

What’s happening:

  • REST Assured can call WireMock like any other server: here, with the headers and query parameters the stub demands.
  • The provider’s rate is a JSON number, so the path reads it as a float, 1.09f.

Checkpoint: run the class again. Four tests pass.

A request that matches no stub gets a 404 whose body reports the closest stub and what differed. Sent to /v2/other, the report was:

1
2
3
4
5
6
7
8
9
10
                                               Request was not matched
                                               =======================

| Closest stub                                             | Request                                                  |
GET                                                        | GET
[path] /v2/rates                                           | /v2/other?base=EUR&symbols=GBP                      <<<<< URL does not match
Authorization: Bearer fx-api-key                           | Authorization: Bearer fx-api-key
X-Client-Id: payments-service                              | X-Client-Id: payments-service
Query: base = EUR                                          | base: EUR
Query: symbols = GBP                                       | symbols: GBP

WireMockExtension.newInstance()...failOnUnmatchedRequests(true) makes the extension fail a test after it runs when any request matched no stub, with the closest stub in the message. It also fails tests that are unmatched on purpose, such as aRequestWithoutTheRightHeadersMatchesNoStub, so turn it on while you debug, or in a class without such tests.

Prove the Provider Wasn’t Called

Reject Invalid Input First

Goal: prove invalid input is rejected before the service calls anyone.

Add this test to the class:

1
2
3
4
5
6
@Test
void invalidInputNeverReachesTheProvider() {
    quotes().body(quoteRequest("EUR", "EUR", "100.00")).when().post("/quotes").then().statusCode(422);

    fxProvider.verify(0, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));
}

What’s happening:

  • A quote from EUR to EUR is invalid, and the service rejects it with 422 and needs two different ISO 4217 currencies ....
  • verify(0, ..) proves no request reached the provider: no wasted call, and no cost. Section 3 covers verification in depth.
  • There’s no stub in this test at all: if the service had called the provider, it would have got a 404.

Checkpoint: run the class again. All five tests pass.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-10 -Dtest=StubbingBasicsTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_10.section_01.StubbingBasicsTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.712 s -- in com.javanibble.module_10.section_01.StubbingBasicsTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In aQuoteUsesTheProvidersRate, change the stub to ratesRequest("EUR", "USD"), and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   StubbingBasicsTest.aQuoteUsesTheProvidersRate:63 1 expectation failed.
Expected status code <201> but was <422>.

The service asked for GBP, the stub only matches USD, and WireMock answered 404. Nothing in the failure mentions the stub: it looks like the provider doesn’t support the currency. This is the trap from the danger callout, and why calling the stub directly, or failOnUnmatchedRequests(true), helps.

Put "GBP" back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
422 with the FX provider doesn't support ..No stub matched, so WireMock answered 404Compare the stub with the request, or call the stub directly
no suitable method found for body(java.lang.String,com.github.tomakehurst...)WireMock’s equalTo(..) was statically importedCall WireMock’s methods through the WireMock class
A stub from one test answers in anotherA hand-started WireMockServer, which isn’t resetUse WireMockExtension, or reset the server after each test
The service calls the real providerThe provider’s URL is hard-codedMake it configurable, and pass fxProvider.baseUrl()

Try It Yourself

Exercise 1: Quote in Another Currency

Add a test called aQuoteInDollars. Stub the provider’s EUR/USD rate as 1.0912, ask for a quote of 100.00 EUR in USD, and check that the rate is "1.0912" and the target amount "109.12".

Hint

Use ratesRequest("EUR", "USD") and ratesBody("EUR", "USD", "1.0912"). The service returns the rate and the amount as strings.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aQuoteInDollars() {
    fxProvider.stubFor(ratesRequest("EUR", "USD").willReturn(WireMock.okJson(ratesBody("EUR", "USD", "1.0912"))));

    quotes()
        .body(quoteRequest("EUR", "USD", "100.00"))
    .when()
        .post("/quotes")
    .then()
        .statusCode(201)
        .body("rate", equalTo("1.0912"))
        .body("targetAmount", equalTo("109.12"));
}

Exercise 2: Reject More Invalid Input

Add a test called moreInvalidInputNeverReachesTheProvider. Send a quote with the amount 100.005, and one with the source currency eur in lower case. Check that both answer 422, that the first has the detail needs two different ISO 4217 currencies and a positive amount with two decimals, and that no request reached the provider.

Hint

The detail is in errors[0].detail. Call verify(0, ..) once, after both requests.

Solution
1
2
3
4
5
6
7
8
9
10
@Test
void moreInvalidInputNeverReachesTheProvider() {
    quotes().body(quoteRequest("EUR", "GBP", "100.005")).when().post("/quotes")
        .then()
            .statusCode(422)
            .body("errors[0].detail", equalTo("needs two different ISO 4217 currencies and a positive amount with two decimals"));
    quotes().body(quoteRequest("eur", "GBP", "100.00")).when().post("/quotes").then().statusCode(422);

    fxProvider.verify(0, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));
}

Summary

You built StubbingBasicsTest, which lets WireMock play the FX provider while REST Assured tests the quote service: a stubbed rate, an exact rounding tie, an unmatched request, a stub called directly, and invalid input that never reaches the provider. The tests no longer depend on the provider’s prices, availability or rates.

  • WireMock plays a dependency your API calls; REST Assured tests your API.
  • WireMockExtension starts WireMock on a free port, and removes the stubs after each test.
  • A stub is a request pattern plus a response; keep the provider’s patterns in one place, and make them strict.
  • WireMock answers 404 when no stub matches, which your service can’t tell from a real one; call the stub directly to see why.
  • verify(..) proves calls were, or weren’t, made.

Here are the commands you used in this guide:

1
2
git clone https://github.com/javanibble/rest-assured-examples.git
mvn test -pl module-10 -Dtest=StubbingBasicsTest

What’s Next

Next: continue with Simulate Provider Faults With WireMock in REST Assured Tests, which makes the provider fail, slow down and send broken answers on demand.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.