Simulate Provider Faults With WireMock in REST Assured Tests
Make a third-party dependency misbehave on demand, covering server errors, a slow provider with withFixedDelay, a reset connection with Fault, broken JSON, a missing value, rate limiting with Retry-After and an unknown currency, and check what your API's clients see.
A real FX provider works almost all the time, which is why it’s useless for testing what happens when it doesn’t. You can’t ask it to answer 500, to take three seconds, to reset the connection, or to send half a JSON document. Those are the cases that cause outages in production, and the ones a test suite most needs to cover. And the question that matters isn’t what the provider does, but what your API’s clients see when it does. In this guide, you’ll make the provider fail in seven ways, one line each, and check your API’s answer every time.
Level: Advanced · Time: 25 minutes · Part of: Module 10: Stubbing Dependencies with WireMock, section 2
What You’ll Build
You’ll build a test class called ProviderFaultsTest with seven tests. Each one requests the same quote, makes the provider misbehave in one way, and checks what the quote service answers: three error statuses, a slow provider, a reset connection, broken JSON and a missing rate.
A provider’s 500 must reach your API’s client as a gateway error that names the cause:
1
{"type":"about:blank","title":"Bad Gateway","status":502,"detail":"The FX provider failed with status 500","instance":"/api/v1/quotes"}
When you’re done, Maven reports seven passing tests:
1
2
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Map the provider’s error statuses.
- Simulate faults a real provider won’t produce.
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 with
WireMockExtensionandFxProviderStubs, as taught in Stub a Dependency With WireMock in REST Assured Tests, and check a response time withtime(..), from Check Every Part of an HTTP Response.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
ProviderFaultsTestin a newsection_02package next to the class from the previous section, and follow every heading below. - Skip ahead: open the finished class (
ProviderFaultsTest.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 checks what your API answers, not how often it called the provider; the retry for a 503 is verified in Verify Outgoing Calls With WireMock in REST Assured Tests.
Understand Provider Faults
The problem. A dependency fails in many ways: error statuses, slowness, broken connections, and 200 answers that aren’t usable. Against a real provider, none of these can be produced on demand, so they go untested, and the first test is the outage. And when they happen, a provider’s error passed on as your own 500 tells your clients that your service is broken.
The concept. WireMock’s response builder can simulate each failure:
| WireMock | Simulates |
|---|---|
serverError(), serviceUnavailable(), notFound() | Error statuses |
aResponse().withStatus(429).withHeader("Retry-After", ..) | Rate limiting |
withFixedDelay(millis) | A slow answer |
withFault(Fault.CONNECTION_RESET_BY_PEER) | A broken connection |
withBody("{\"rates\": ") | A malformed body |
Your API’s answer should tell its clients what happened. 502 Bad Gateway and 504 Gateway Timeout are the gateway statuses: they say “something behind me failed”, so a client can retry, or alert the right team.
When to use each. Simulate every failure your API handles, and every one it should. Check the status, the detail and, for a timeout, how long the client waited.
Test what your clients see when the dependency fails, not only when it works.
Meet the API Under Test
Every test sends the same request to the quote service, POST /api/v1/quotes for 100.00 EUR in GBP. The service maps each provider failure to its own answer, always as application/problem+json:
| The provider… | Our API answers | detail |
|---|---|---|
answers 500 | 502 | The FX provider failed with status 500 |
answers 503 | Retries once; 502 if it fails again | The FX provider failed with status 503 |
answers 429 with Retry-After: 30 | 503 with Retry-After: 30 | The FX provider is rate limiting us |
answers 404 | 422 | the FX provider doesn't support EUR/GBP, in errors |
| takes longer than a second | 504 | The FX provider didn't answer within PT1S |
| resets the connection | 502 | The FX provider is unreachable: IOException |
| sends broken JSON | 502 | The FX provider sent an invalid response |
| sends no rate for GBP | 502 | The FX provider sent no rate for GBP |
Your tests check these values:
- The status, and the
detailthat names the cause. - The
Retry-Afterheader for rate limiting. - The time the client waited for a slow provider.
Map the Provider’s Error Statuses
Set Up the Test Class
Goal: create the test class with WireMock, the service, and a helper that requests the same quote every time.
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
48
49
50
51
52
package com.javanibble.module_10.section_02;
import static com.javanibble.module_10.support.FxProviderStubs.quoteRequest;
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.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
import com.javanibble.fx.QuoteService;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
import java.util.concurrent.TimeUnit;
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 ProviderFaultsTest {
@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 requestAQuote() {
return given().baseUri(service.baseUri()).port(service.port())
.contentType(ContentType.JSON)
.body(quoteRequest("EUR", "GBP", "100.00"))
.when().post("/api/v1/quotes")
.then();
}
}
What’s happening:
- WireMock and the service start as in the previous section, with the service calling WireMock.
requestAQuote()sends the same quote and returns theValidatableResponse, so each test adds only its checks. The tests differ only in how the provider answers.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Turn a Server Error Into Bad Gateway
Goal: prove a provider’s 500 doesn’t leak out as your API’s 500.
Add this test to the class:
1
2
3
4
5
6
7
8
9
@Test
void aServerErrorBecomesBadGateway() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.serverError()));
requestAQuote()
.statusCode(502)
.contentType("application/problem+json")
.body("detail", equalTo("The FX provider failed with status 500"));
}
What’s happening:
serverError()answers500to the service’s call.- The service answers
502 Bad Gateway, as a problem detail that names the provider’s status.
Checkpoint: run ProviderFaultsTest from your IDE. One test runs and passes.
Pass On Rate Limiting
Goal: prove the provider’s Retry-After reaches your API’s client.
Add this test to the class:
1
2
3
4
5
6
7
@Test
void rateLimitingIsPassedOnWithRetryAfter() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(
WireMock.aResponse().withStatus(429).withHeader("Retry-After", "30")));
requestAQuote().statusCode(503).header("Retry-After", "30");
}
What’s happening:
aResponse()builds any response: here429 Too Many RequestswithRetry-After: 30.- The provider is rate limiting your service, not your client, so the service answers
503 Service UnavailablewithThe FX provider is rate limiting us. - It passes the same
Retry-Afteron, so the client knows when trying again is worth it.
Checkpoint: run the class again. Two tests pass.
Treat an Unknown Currency as the Client’s Problem
Goal: prove a provider’s 404 is reported as a problem with the client’s input.
Add this test to the class:
1
2
3
4
5
6
@Test
void anUnknownCurrencyIsTheClientsProblem() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.notFound()));
requestAQuote().statusCode(422).body("errors[0].field", equalTo("currency"));
}
What’s happening:
- A provider
404means it doesn’t know the currency pair. - That’s a problem with the client’s input, so the service answers
422with a field error oncurrency, not a gateway error.
Checkpoint: run the class again. Three tests pass.
Simulate Faults a Real Provider Won’t Produce
Time Out a Slow Provider
Goal: prove your API gives up on a slow provider, and doesn’t keep its client waiting.
Add this test to the class:
1
2
3
4
5
6
7
8
9
@Test
void aSlowProviderBecomesGatewayTimeout() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(
WireMock.okJson("{\"rates\": {\"GBP\": 0.85}}").withFixedDelay(3000)));
requestAQuote()
.statusCode(504)
.time(lessThan(2500L), TimeUnit.MILLISECONDS); // our API gave up after about a second
}
What’s happening:
withFixedDelay(3000)makes the provider wait three seconds before answering.- The service’s timeout is one second, so it answers
504 Gateway TimeoutwithThe FX provider didn't answer within PT1S. In a check, the client got the answer after 1,010 milliseconds. - The
time(..)check proves what matters: the client wasn’t kept waiting for the slow provider. A service without a timeout would also answer eventually, after the provider’s full delay.
Checkpoint: run the class again. Four tests pass, the last in about a second.
Keep stub delays a little above the service’s timeout, not far above it. A delay only has to prove the timeout fires; a 30-second delay makes a 30-second test the day the timeout goes missing.
Break the Connection
Goal: simulate a connection that closes without an HTTP response.
Add this test to the class:
1
2
3
4
5
6
7
@Test
void aResetConnectionBecomesBadGateway() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(
WireMock.aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));
requestAQuote().statusCode(502).body("detail", containsString("unreachable"));
}
What’s happening:
Fault.CONNECTION_RESET_BY_PEERcloses the connection without an HTTP response.- The service’s HTTP client throws an
IOException, and the service answers502withThe FX provider is unreachable: IOException. - WireMock has three other faults,
EMPTY_RESPONSE,MALFORMED_RESPONSE_CHUNKandRANDOM_DATA_THEN_CLOSE; Exercise 2 tries them all.
Checkpoint: run the class again. Five tests pass.
Send a Broken or Incomplete Body
Goal: prove a 200 that isn’t usable doesn’t become a 500 in your API.
Add these tests to the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void brokenJsonBecomesBadGateway() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(
WireMock.aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("{\"rates\": ")));
requestAQuote().statusCode(502).body("detail", equalTo("The FX provider sent an invalid response"));
}
@Test
void aMissingRateBecomesBadGateway() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.okJson("{\"rates\": {\"USD\": 1.09}}")));
requestAQuote().statusCode(502).body("detail", equalTo("The FX provider sent no rate for GBP"));
}
What’s happening:
- Half a JSON document can’t be parsed, so the service answers
The FX provider sent an invalid response. - A valid document without the rate asked for answers
The FX provider sent no rate for GBP. - Neither turns into a
NullPointerExceptionand a500in your API.
Checkpoint: run the class again. All seven tests pass.
A
200doesn’t mean the answer is usable. In a check, two more200answers also got502: an HTML maintenance page, withThe FX provider sent an invalid response, and a rate sent as the string"0.85", withThe FX provider sent no rate for GBP. Test malformed bodies and unexpected types, not only error statuses.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-10 -Dtest=ProviderFaultsTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_10.section_02.ProviderFaultsTest
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.195 s -- in com.javanibble.module_10.section_02.ProviderFaultsTest
[INFO]
[INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
About a second of that is the slow-provider test, which waits for the service’s timeout.
Make a Test Fail
In aSlowProviderBecomesGatewayTimeout, change the delay from 3000 to 500 milliseconds, and run the command again. You should see a result similar to the following:
1
2
3
[ERROR] Failures:
[ERROR] ProviderFaultsTest.aSlowProviderBecomesGatewayTimeout:76 1 expectation failed.
Expected status code <504> but was <201>.
Half a second is within the service’s one-second timeout, so the provider’s answer arrived in time, and the client got a quote. A delay only simulates a timeout when it’s longer than the timeout.
Put 3000 back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
201 instead of 504 | The stub’s delay is shorter than the service’s timeout | Use a delay above the timeout, such as 3000 for one second |
422 with doesn't support EUR/GBP in every test | The stub doesn’t match, so WireMock answers 404 | Build the stub from ratesRequest("EUR", "GBP") |
| The slow test takes as long as the delay | The service has no timeout on its call | Set a timeout on the service’s HTTP client |
500 from your API | The service doesn’t handle this failure | Map it to 502, 503 or 504 with a detail |
Try It Yourself
Exercise 1: Rate Limiting Without Retry-After
Add a test called rateLimitingWithoutRetryAfter. Stub a 429 with no Retry-After header, and check that the service answers 503 with the detail The FX provider is rate limiting us, and no Retry-After header of its own.
Hint
Use WireMock.aResponse().withStatus(429). Check the missing header with header("Retry-After", nullValue()), and import org.hamcrest.Matchers.nullValue.
Solution
1
2
3
4
5
6
7
8
9
@Test
void rateLimitingWithoutRetryAfter() {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.aResponse().withStatus(429)));
requestAQuote()
.statusCode(503)
.header("Retry-After", nullValue())
.body("detail", equalTo("The FX provider is rate limiting us"));
}
Add import static org.hamcrest.Matchers.nullValue; to the class.
Exercise 2: Try Every Connection Fault
Add a parameterized test called everyConnectionFaultBecomesBadGateway that runs once for every value of WireMock’s Fault enum. Check that each one answers 502 with the detail The FX provider is unreachable: IOException.
Hint
Use @ParameterizedTest with @EnumSource(Fault.class), from Write Parameterized API Tests With REST Assured, and take a Fault parameter.
Solution
1
2
3
4
5
6
7
@ParameterizedTest(name = "{0} becomes Bad Gateway")
@EnumSource(Fault.class)
void everyConnectionFaultBecomesBadGateway(Fault fault) {
fxProvider.stubFor(ratesRequest("EUR", "GBP").willReturn(WireMock.aResponse().withFault(fault)));
requestAQuote().statusCode(502).body("detail", equalTo("The FX provider is unreachable: IOException"));
}
Add import org.junit.jupiter.params.ParameterizedTest; and import org.junit.jupiter.params.provider.EnumSource; to the class. The test runs four times, for CONNECTION_RESET_BY_PEER, EMPTY_RESPONSE, MALFORMED_RESPONSE_CHUNK and RANDOM_DATA_THEN_CLOSE.
Summary
You built ProviderFaultsTest, which makes the FX provider answer with three error statuses, wait too long, reset the connection, send broken JSON and leave out the rate, and checks what the quote service’s clients see each time. No provider failure reaches them as a 500.
- WireMock simulates failures a real provider won’t produce on demand: error statuses,
429withRetry-After,withFixedDelay(..),withFault(..)and malformed bodies. - Check what your API’s clients see:
502for a provider failure,504for a timeout,503withRetry-Afterfor rate limiting, and422when the client’s input is the problem. - Check the time on a timeout, not only the status, and keep stub delays a little above the timeout.
- A
200can still be unusable: test broken JSON, missing values and unexpected types.
Here are the commands you used in this guide:
1
mvn test -pl module-10 -Dtest=ProviderFaultsTest
What’s Next
Next: continue with Verify Outgoing Calls With WireMock in REST Assured Tests, which checks the requests your API sends to the provider, including the retry for a 503.
The code:
- The finished test class:
ProviderFaultsTest.java - The code and run commands for this module: Module 10 README
Go deeper:
- WireMock: Simulating Faults, for delays and every fault.
- RFC 9110, section 15.6.3: 502 Bad Gateway and section 15.6.5: 504 Gateway Timeout, for the gateway statuses.
- RFC 6585, for
429 Too Many Requests.
Related guides:
- Configure Timeouts, Redirects and Charsets in REST Assured, for the same timeout idea on the test’s own requests.
- Check Every Part of an HTTP Response, for
time(..)and why its limits should be generous.
