Use Response Templates and Scenarios in WireMock Stubs
Build stubs that adapt, covering one templated stub for every currency with response-template and {{request.query..}}, and stateful scenarios in which the provider fails twice and recovers, or fails once and is hidden by a retry.
The stubs so far answer the same way every time. That’s fine for one currency pair, but a test of three currencies needs three stubs that are almost identical. And some behaviour can’t be expressed with a fixed answer at all: a provider that’s down for two requests and then comes back. Without that, a retry can be shown to happen, but not to help. In this guide, you’ll build a stub that answers from the request, and stubs that change their answer over time.
Level: Advanced · Time: 25 minutes · Part of: Module 10: Stubbing Dependencies with WireMock, section 4
What You’ll Build
You’ll build a test class called TemplatingAndScenariosTest with three tests. One uses a single templated stub for three currencies; two use scenarios, a provider that fails twice and recovers, and one that fails once and is saved by the retry.
The outage scenario moves through its states with every call the service makes:
| Provider call | Scenario state | Answer | Next state |
|---|---|---|---|
| 1st (quote 1) | Started | 503 | failed once |
| 2nd (quote 1, retry) | failed once | 503 | failed twice |
| 3rd (quote 2) | failed twice | 200 | stays |
When you’re done, Maven reports three passing tests:
1
2
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Build an answer from the request.
- Change the answer over time.
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 stub the provider and simulate its errors, as taught in Stub a Dependency With WireMock in REST Assured Tests and Simulate Provider Faults With WireMock in REST Assured Tests, and you know the service retries a
503once, from Verify Outgoing Calls With WireMock in REST Assured Tests.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
TemplatingAndScenariosTestin a newsection_04package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
TemplatingAndScenariosTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Stub a Dependency With WireMock in REST Assured Tests.
Out of scope: this guide uses one template helper, request.query. It doesn’t cover WireMock’s other helpers, such as dates, random values or JSON paths into the request body.
Understand Templates and Scenarios
The problem. A fixed stub gives a fixed answer. When the answer must echo the request, such as the currency asked for, each case needs its own stub. And when the answer must change between calls, such as a provider that recovers, a fixed stub can’t express it at all.
The concept. WireMock has a feature for each:
- A response template is a body with placeholders, filled from the request. `` becomes the
symbolsquery parameter. WireMock processes it only when the stub asks, withwithTransformers("response-template"). - A scenario is a small state machine shared by several stubs.
inScenario(name)puts a stub in it,whenScenarioStateIs(state)makes the stub match only in that state, andwillSetStateTo(state)moves the scenario on when it matches. Every scenario starts inScenario.STARTED, the stringStarted.
| Need | Use |
|---|---|
| The same answer every time | A plain stub |
| An answer that echoes the request | A response template |
| An answer that changes over time | A scenario |
| Different answers for different requests | Several plain stubs with different request patterns |
When to use each. Use a template when the answer must echo part of the request, and keep it to echoing: a template that calculates is a second implementation of the provider. Use a scenario to test behaviour across calls, such as retries and recovery.
Echo the request in a template, and count every call in a scenario.
Meet the API Under Test
The tests request quotes from EUR to a target currency, through the quote service from the earlier sections. Two of its rules matter here:
- The quote’s
targetAmountissourceAmount × rate, and itstargetCurrencyis the one asked for. - A provider
503is retried once. If the retry fails too, the client gets502; if it succeeds, the client gets a quote.
Your tests check these values:
targetCurrencyandtargetAmountfor each currency.- The status of each quote while the provider fails and recovers.
- The
ratefrom a quote saved by the retry.
Build an Answer From the Request
Set Up the Test Class
Goal: create the test class with WireMock, the service, and a helper that requests a quote in a target currency.
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
45
46
47
package com.javanibble.module_10.section_04;
import static com.javanibble.module_10.support.FxProviderStubs.quoteRequest;
import static com.javanibble.module_10.support.FxProviderStubs.ratesBody;
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 com.github.tomakehurst.wiremock.stubbing.Scenario;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
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 TemplatingAndScenariosTest {
@RegisterExtension
static WireMockExtension fxProvider = WireMockExtension.newInstance()
.options(wireMockConfig().dynamicPort())
.build();
private static QuoteService service;
@BeforeAll
static void startService() {
service = QuoteService.start(fxProvider.baseUrl());
}
@AfterAll
static void stopService() {
service.close();
}
private static ValidatableResponse quote(String target) {
return given().baseUri(service.baseUri()).port(service.port())
.contentType(ContentType.JSON).body(quoteRequest("EUR", target, "100.00"))
.when().post("/api/v1/quotes")
.then();
}
}
What’s happening:
quote(target)requests 100.00 EUR in the given currency, and returns the response to check.WireMockExtensionremoves stubs and scenarios after each test: at the start of the next test, there were no scenarios left. A scenario’s state never leaks from one test into another.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Serve Every Currency From One Stub
Goal: answer every currency the service asks for with one templated stub.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void oneTemplatedStubForEveryCurrency() {
// is replaced by the symbols query parameter of each request.
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates"))
.willReturn(WireMock.aResponse()
.withHeader("Content-Type", "application/json")
.withBody("{\"base\": \"\", \"rates\": {\"\": 2.0}}")
.withTransformers("response-template")));
quote("GBP").statusCode(201).body("targetCurrency", equalTo("GBP")).body("targetAmount", equalTo("200.00"));
quote("CHF").statusCode(201).body("targetCurrency", equalTo("CHF"));
quote("JPY").statusCode(201).body("targetCurrency", equalTo("JPY"));
}
What’s happening:
- For
GET /v2/rates?base=EUR&symbols=CHF, the body becomes{"base": "EUR", "rates": {"CHF": 2.0}}: the rate is under the key the service asked for. withTransformers("response-template")turns templating on for this stub only.- One stub answers all three quotes, each with a rate of
2.0, so100.00becomes200.00.
Checkpoint: run TemplatingAndScenariosTest from your IDE. One test runs and passes.
Without
withTransformers("response-template"), WireMock sends the placeholders as they are. Called directly, the stub answered{"base": "", "rates": {"": 2.0}}, a rate for a currency literally called ``, and the quote failed with502andThe FX provider sent no rate for GBP. The failure points at the provider’s data, not at the stub.
Change the Answer Over Time
Fail Twice, Then Recover
Goal: prove the service gives up after one retry, and works again once the provider is back.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void theProviderFailsTwiceThenRecovers() {
// States: Started -> (503) -> failed once -> (503) -> failed twice -> (200, for good)
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("outage")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(WireMock.serviceUnavailable())
.willSetStateTo("failed once"));
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("outage")
.whenScenarioStateIs("failed once")
.willReturn(WireMock.serviceUnavailable())
.willSetStateTo("failed twice"));
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("outage")
.whenScenarioStateIs("failed twice")
.willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));
quote("GBP").statusCode(502); // 503, retry, 503: our API gives up
quote("GBP").statusCode(201); // the provider is back
}
What’s happening:
- Three stubs share the scenario
outage. Each matches in one state; the first two move it on. - The first quote uses up both failures, its first try and its retry, and gets
502. - The second quote finds the provider recovered. The last stub has no
willSetStateTo(..), so the scenario stays infailed twice, and every later call gets200. - The test proves two things at once: the service gives up after one retry, and it doesn’t stay broken once the provider is back.
Checkpoint: run the class again. Two tests pass.
Count every call the service makes, not every request the test sends. A retry is a provider call too, and moves the scenario on. Exercise 2 shows what happens with one more failure.
Hide One Failure With the Retry
Goal: prove the retry saves a request when the provider only blips.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void oneFailureIsHiddenByTheRetry() {
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("blip")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(WireMock.serviceUnavailable())
.willSetStateTo("recovered"));
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("blip")
.whenScenarioStateIs("recovered")
.willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));
quote("GBP").statusCode(201).body("rate", equalTo("0.85"));
}
What’s happening:
- The provider fails once, the service retries, the second call succeeds, and the client gets its quote without knowing.
- A stub that always answers
503can prove that a retry happens. Only a scenario that recovers can prove the retry helps.
Checkpoint: run the class again. All three tests pass.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-10 -Dtest=TemplatingAndScenariosTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_10.section_04.TemplatingAndScenariosTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.727 s -- in com.javanibble.module_10.section_04.TemplatingAndScenariosTest
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In oneTemplatedStubForEveryCurrency, remove .withTransformers("response-template"), keeping the closing parentheses, and run the command again. You should see a result similar to the following:
1
2
3
[ERROR] Failures:
[ERROR] TemplatingAndScenariosTest.oneTemplatedStubForEveryCurrency:65 1 expectation failed.
Expected status code <201> but was <502>.
Without the transformer, the placeholders reach the service as they are, and it finds no rate for GBP. Nothing in the failure mentions templating, which is why this mistake is hard to spot: look at the stub first when a templated test fails with no rate.
Put .withTransformers("response-template") back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
502 with sent no rate for .. from a templated stub | The stub doesn’t ask for templating | Add withTransformers("response-template") |
| A scenario answers the “recovered” stub too early | A retry moved the scenario on | Count the service’s calls, including retries |
| A scenario starts in the wrong state | A hand-started WireMockServer kept the state from an earlier test | Use WireMockExtension, or call resetScenarios() |
404 from WireMock in a scenario | No stub matches the current state | Add a stub for every state the scenario reaches |
Try It Yourself
Exercise 1: Check the Scenario’s State
Add a test called theBlipScenarioEndsRecovered. Set up the blip scenario from oneFailureIsHiddenByTheRetry, request a quote, and check that the scenario’s state is now recovered, and that the provider received two calls.
Hint
fxProvider.getAllScenarios().getScenarios() returns the scenarios; take the first one, and call getState(). Count the calls with verify(2, ..). Import assertEquals.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void theBlipScenarioEndsRecovered() {
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("blip")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(WireMock.serviceUnavailable())
.willSetStateTo("recovered"));
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("blip")
.whenScenarioStateIs("recovered")
.willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));
quote("GBP").statusCode(201);
assertEquals("recovered", fxProvider.getAllScenarios().getScenarios().getFirst().getState());
fxProvider.verify(2, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));
}
Add import static org.junit.jupiter.api.Assertions.assertEquals; to the class.
Exercise 2: Survive a Longer Outage
Add a test called theProviderFailsThreeTimesThenRecovers. Build a scenario in which the provider answers 503 three times and then 200. Check that the first quote gets 502, the second 201, and that the provider received four calls in total.
Hint
The first quote makes two calls, its try and its retry. The second quote’s first call is the third failure, and its retry is the first success. Use states such as Started, 1, 2 and 3, and build the three failing stubs in a loop.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void theProviderFailsThreeTimesThenRecovers() {
String[] states = {Scenario.STARTED, "1", "2", "3"};
for (int i = 0; i < 3; i++) {
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("long outage")
.whenScenarioStateIs(states[i])
.willReturn(WireMock.serviceUnavailable())
.willSetStateTo(states[i + 1]));
}
fxProvider.stubFor(WireMock.get(WireMock.urlPathEqualTo("/v2/rates")).inScenario("long outage")
.whenScenarioStateIs("3")
.willReturn(WireMock.okJson(ratesBody("EUR", "GBP", "0.85"))));
quote("GBP").statusCode(502); // calls 1 and 2: 503, 503
quote("GBP").statusCode(201); // call 3: 503, call 4: 200
fxProvider.verify(4, WireMock.getRequestedFor(WireMock.urlPathEqualTo("/v2/rates")));
}
Summary
You built TemplatingAndScenariosTest, which serves three currencies from one templated stub, and uses scenarios to make the provider fail twice and recover, and fail once and be saved by the retry. The retry is now proven to give up when it should, and to help when it can.
- A response template builds the answer from the request; with
withTransformers("response-template"), `` lets one stub serve every currency. - Without the transformer, placeholders are sent as they are, and the failure points at the provider’s data.
- A scenario is a state machine:
inScenario(..),whenScenarioStateIs(..)andwillSetStateTo(..), starting inScenario.STARTED. - Count every call the service makes, including retries, when you plan a scenario’s states.
WireMockExtensionresets scenarios after each test, along with the stubs.
Here are the commands you used in this guide:
1
mvn test -pl module-10 -Dtest=TemplatingAndScenariosTest
What’s Next
Next: you’ve finished Module 10. Continue with Module 11: Spring Boot Integration, starting with Test a Spring Controller With RestAssuredMockMvc in Standalone Mode, which tests a Spring MVC controller with REST Assured’s syntax and no server.
The code:
- The finished test class:
TemplatingAndScenariosTest.java - The code and run commands for this module: Module 10 README
Go deeper:
- WireMock: Response Templating, for every helper a template can use.
- WireMock: Stateful Behaviour, for scenarios and their states.
Related guides:
- Verify Outgoing Calls With WireMock in REST Assured Tests, for counting the calls a scenario sees.
- Test API Workflows With REST Assured, for state machines on your own API’s side.
