Read REST Assured Failure Messages
Learn to read REST Assured failure messages, why a then() chain stops at its first failing call, and how one body(..) call reports all its mismatches at once.
An account test fails on the build server at 2 a.m. You fix the field it names, push, wait twenty minutes, and it fails again on a different field of the same account. In this guide, you’ll learn to read a REST Assured failure message, and write your checks so that one red run reports everything that’s wrong.
Level: Beginner · Time: 20 minutes · Part of: Module 1: Foundations, section 6
What You’ll Build
You’ll build two test classes. FailureMessagesTest captures failures with assertThrows and checks their messages, so the build stays green. DeliberatelyFailingTest fails on purpose, so you can read real red output. A tag keeps it out of the normal build.
One of the failures you’ll read comes from this request:
1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1003 HTTP/1.1
Host: localhost:<port>
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{"id":"acc-1003","owner":"Jan Jansen","balance":-42.10,"status":"BLOCKED", ...}
When you’re done, Maven reports four passing tests for the capturing class:
1
2
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Read the shape of a failure message.
- See a chain stop at its first failure.
- Report every mismatch in one
body(..)call. - Run a class of deliberately failing tests.
What You Need
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can check status codes, headers and body paths, as taught in Check Every Part of an HTTP Response, and log on failure, as taught in Log REST Assured Requests and Responses.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create both classes in a new
section_06package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished classes (
FailureMessagesTest.javaandDeliberatelyFailingTest.java) and read along. You can run them at any time with the commands in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Send Your First REST Assured Request.
Out of scope: this guide doesn’t cover response specifications, which apply the same reporting rules to a whole set of checks; they’re taught in Module 5.
Understand REST Assured Failures
The problem. When a test fails on the build server, the failure message is often all you have. If it doesn’t name the field, you open the body. If it reports only the first of three problems, you need three runs to find them all.
The concept. A failed expectation throws a plain java.lang.AssertionError, so JUnit reports it like any other failed assertion. Its message always has the same shape:
- A count:
1 expectation failed.or2 expectations failed. - One paragraph per failure: what was checked, then what was expected and what was found.
After then(), REST Assured validates eagerly. Each call, such as statusCode(..), header(..) or body(..), checks the response as soon as it’s made, and the first failing call throws. The rest of the chain never runs. All path and matcher pairs inside a single body(..) call are one check, though, so its message reports every mismatch in it.
When to group checks. Put paths that describe one object into one body(..) call, so one run reports all their mismatches. Keep separate calls for checks that only make sense once an earlier one holds, such as body checks after a status check: there’s no point reading fields from a 404.
Group the checks that describe one thing, so one red run tells the whole story.
Meet the API Under Test
This guide uses the account endpoints of the Accounts API, under the base path /api/v1. The tests read these values:
| Request | Field or part | Actual value |
|---|---|---|
GET /accounts | count | 4 |
GET /accounts | accounts.id | acc-1001 … acc-1004 |
GET /accounts | Content type | application/json; charset=utf-8 |
GET /accounts/acc-1001 | Cache-Control | no-store |
GET /accounts/acc-1001 | owner, type | Anna de Vries, CURRENT |
GET /accounts/acc-1003 | status, balance | BLOCKED, -42.10 |
GET /accounts/acc-1004 | currency | GBP |
GET /accounts/acc-9999 | Status code | 404 |
For acc-1003, the full response looks like the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
Cache-control: no-store
{
"id": "acc-1003",
"iban": "NL20INGB0001234567",
"owner": "Jan Jansen",
"type": "CURRENT",
"currency": "EUR",
"balance": -42.10,
"status": "BLOCKED",
"openedOn": "2017-11-30"
}
Every test in this guide expects something different from these values on purpose, so you can read the message that results.
Read the Shape of a Failure Message
Set Up the Capturing Class
Goal: create a test class that can check failure messages without failing the build.
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
package com.javanibble.module_01.section_06;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.javanibble.accounts.AccountsApi;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class FailureMessagesTest {
private static AccountsApi api;
@BeforeAll
static void startApi() {
api = AccountsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification accountsApi() {
return given()
.baseUri(api.baseUri())
.port(api.port())
.basePath(AccountsApi.BASE_PATH);
}
}
What’s happening:
- The lifecycle methods and the
accountsApi()helper are the same as in the previous sections. assertThrows,assertTrueandassertFalseare new. Because a failure is an ordinaryAssertionError,assertThrowscan catch it and hand you its message.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Capture a Wrong Status Code
Goal: fail a status check on purpose and check the message.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aWrongStatusCodeNamesExpectedAndActual() {
AssertionError error = assertThrows(AssertionError.class, () ->
accountsApi()
.when()
.get("/accounts/{id}", "acc-1001")
.then()
.statusCode(404));
String message = error.getMessage();
assertTrue(message.startsWith("1 expectation failed."), message);
assertTrue(message.contains("Expected status code <404> but was <200>"), message);
}
What’s happening:
acc-1001exists, so the API answers200, andstatusCode(404)fails.assertThrows(..)runs the chain, catches theAssertionErrorand returns it. If nothing is thrown,assertThrowsfails instead.- The message starts with the count, then gives the expected and actual status in one line.
- Passing
messageas the last argument toassertTrueprints the whole message if the check fails.
Checkpoint: run FailureMessagesTest from your IDE. One test runs and passes.
Capture a Wrong Body Value
Goal: fail a body check on purpose and check that the message names the path.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aWrongBodyValueNamesThePath() {
AssertionError error = assertThrows(AssertionError.class, () ->
accountsApi()
.when()
.get("/accounts")
.then()
.body("count", equalTo(5)));
String message = error.getMessage();
assertTrue(message.contains("JSON path count doesn't match."), message);
assertTrue(message.contains("Expected: <5>"), message);
assertTrue(message.contains("Actual: <4>"), message);
}
What’s happening:
- A body failure has three lines: the path that was read, then
Expected:andActual:. - The path tells you which field to look at without opening the body.
- Numbers appear in angle brackets, such as
<5>, while strings appear without them.
Checkpoint: run the class again. Two tests pass.
See a Chain Stop at Its First Failure
Fail on a Header Before the Body
Goal: show that a check after a failing call is never run.
The header and the owner are both wrong here, but only one is reported:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void aThenChainStopsAtTheFirstFailingCall() {
AssertionError error = assertThrows(AssertionError.class, () ->
accountsApi()
.when()
.get("/accounts/{id}", "acc-1001")
.then()
.statusCode(200)
.header("Cache-Control", "max-age=60")
.body("owner", equalTo("Jan Jansen")));
String message = error.getMessage();
assertTrue(message.startsWith("1 expectation failed."), message);
assertTrue(message.contains("Expected header \"Cache-Control\""), message);
assertFalse(message.contains("owner"), message);
}
What’s happening:
statusCode(200)is checked at once and holds.header("Cache-Control", "max-age=60")is checked at once and fails, because the value isno-store. It throws straight away.body("owner", ..)is never reached, soassertFalse(message.contains("owner"), ..)passes: the message doesn’t mention the owner at all.
The full header message lists every header the response did have, which helps when a header is missing or misspelled:
1
2
3
4
5
6
7
1 expectation failed.
Expected header "Cache-Control" was not "max-age=60", was "no-store". Headers are:
Date=Sat, 21 Nov 2026 18:18:19 GMT
Content-type=application/json; charset=utf-8
X-request-id=5f3b91ec-45ad-4960-9dcb-00f439d20c64
Content-length=163
Cache-control=no-store
Checkpoint: run the class again. Three tests pass.
The owner is also wrong, but this run doesn’t tell you. You’d fix the header, run again, and only then find the second problem. On a slow build, that’s the twenty-minute loop from the opening.
Report Every Mismatch in One body(..) Call
Group the Body Checks
Goal: check three fields in one call and get every mismatch in one message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void allPathsOfOneBodyCallAreReportedTogether() {
AssertionError error = assertThrows(AssertionError.class, () ->
accountsApi()
.when()
.get("/accounts/{id}", "acc-1001")
.then()
.body("owner", equalTo("Jan Jansen"),
"currency", equalTo("EUR"),
"type", equalTo("SAVINGS")));
String message = error.getMessage();
assertTrue(message.startsWith("2 expectations failed."), message);
assertTrue(message.contains("JSON path owner doesn't match."), message);
assertTrue(message.contains("JSON path type doesn't match."), message);
}
What’s happening:
ownerandtypeare wrong, andcurrencyis right.- All three pairs are one check, so REST Assured evaluates every pair before it throws.
- The count says
2 expectations failed., and the message has one paragraph for each wrong field:
1
2
3
4
5
6
7
8
2 expectations failed.
JSON path owner doesn't match.
Expected: Jan Jansen
Actual: Anna de Vries
JSON path type doesn't match.
Expected: SAVINGS
Actual: CURRENT
Checkpoint: run the class again. All four tests pass.
Run Deliberately Failing Tests
Captured messages keep the build green, but on the build server you’ll read real red output. The second class produces it.
Tag the Class So the Build Skips It
Goal: create a class whose tests fail on purpose, without breaking mvn test.
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
package com.javanibble.module_01.section_06;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import com.javanibble.accounts.AccountsApi;
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.Tag;
import org.junit.jupiter.api.Test;
@Tag("expected-failure-tests")
class DeliberatelyFailingTest {
private static AccountsApi api;
@BeforeAll
static void startApi() {
api = AccountsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification accountsApi() {
return given()
.baseUri(api.baseUri())
.port(api.port())
.basePath(AccountsApi.BASE_PATH);
}
}
What’s happening:
@Tag("expected-failure-tests")marks every test in the class.- The parent POM sets the Maven property
excludedGroupstoexpected-failure-tests, so Surefire skips tagged tests. -DexcludedGroups=noneon the command line overrides the property and runs them.
Checkpoint: the class compiles. There are no tests yet.
Add the Failing Tests
Goal: fail once on each part of the response, without catching the error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
void wrongStatusCode() {
accountsApi().when().get("/accounts/{id}", "acc-9999").then().statusCode(200);
}
@Test
void wrongBodyValue() {
accountsApi().when().get("/accounts/{id}", "acc-1004").then().body("currency", equalTo("EUR"));
}
@Test
void missingItemsInAList() {
accountsApi().when().get("/accounts").then().body("accounts.id", hasItems("acc-1001", "acc-2001"));
}
@Test
void wrongContentType() {
accountsApi().when().get("/accounts").then().contentType(ContentType.XML);
}
What’s happening:
- Each test makes one wrong check, so JUnit reports it as a real failure.
acc-2001doesn’t exist, sohasItems(..)fails even thoughacc-1001is in the list.- The list endpoint returns JSON, so
ContentType.XMLfails.
Checkpoint: run the class with the override:
1
mvn test -pl module-01 -Dtest=DeliberatelyFailingTest -DexcludedGroups=none
All four tests fail. Two of the messages are new:
1
2
3
4
5
JSON path accounts.id doesn't match.
Expected: (a collection containing "acc-1001" and a collection containing "acc-2001")
Actual: <[acc-1001, acc-1002, acc-1003, acc-1004]>
Expected content-type "XML" doesn't match actual content-type "application/json; charset=utf-8".
The Expected line of a list failure is the Hamcrest description of the matcher, and the Actual line is the whole collected list.
Combine Several Failures With Logging
Goal: produce the richest failure output: several mismatches, with the request and response printed next to them.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void severalFailuresInOneBodyCall() {
accountsApi()
.log().ifValidationFails()
.when()
.get("/accounts/{id}", "acc-1003")
.then()
.log().ifValidationFails()
.statusCode(200)
.body("status", equalTo("ACTIVE"),
"balance", equalTo(-42.10),
"owner", equalTo("Jan Jansen"));
}
What’s happening:
log().ifValidationFails()on both sides prints the request and response only because the test fails.statusCode(200)holds, so the chain reaches thebody(..)call.statusis wrong, because the account isBLOCKED.balanceis wrong too, because-42.10is adoubleand REST Assured reads aFloat.owneris right.
Checkpoint: run the command again. All five tests fail, and this one prints the logged request and response, followed by:
1
2
3
4
5
6
7
8
2 expectations failed.
JSON path status doesn't match.
Expected: ACTIVE
Actual: BLOCKED
JSON path balance doesn't match.
Expected: <-42.1>
Actual: <-42.1F>
The build ends with BUILD FAILURE and Tests run: 5, Failures: 5. That’s the expected result.
When
ExpectedandActuallook the same, compare the types. TheFin<-42.1F>shows the actual value is aFloat, which is the pitfall from Check Every Part of an HTTP Response.
Run the Tests
Run the capturing class from the repository root:
1
mvn test -pl module-01 -Dtest=FailureMessagesTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_01.section_06.FailureMessagesTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.403 s -- in com.javanibble.module_01.section_06.FailureMessagesTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
A plain mvn test skips DeliberatelyFailingTest. Run it only with -DexcludedGroups=none, as in the previous step.
Make a Test Fail
In aWrongStatusCodeNamesExpectedAndActual, change statusCode(404) to statusCode(200) and run the command again. You should see a result similar to the following:
1
2
[ERROR] FailureMessagesTest.aWrongStatusCodeNamesExpectedAndActual -- Time elapsed: 0.002 s <<< FAILURE!
org.opentest4j.AssertionFailedError: Expected java.lang.AssertionError to be thrown, but nothing was thrown.
The status check now holds, so REST Assured throws nothing, and assertThrows fails instead. This message comes from JUnit, which is how you tell a broken capturing test from a REST Assured failure.
Change statusCode(200) back to statusCode(404) and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
DeliberatelyFailingTest reports Tests run: 0 | The expected-failure-tests tag is excluded by default | Add -DexcludedGroups=none |
Expected java.lang.AssertionError to be thrown, but nothing was thrown. | The check inside assertThrows passes | Make the expected value differ from the actual one |
An assertTrue(message.contains(..)) fails after a library upgrade | The wording of a REST Assured message changed | Read the printed message and assert on its stable parts, such as the path name |
Try It Yourself
Exercise 1: Capture a Wrong Content Type
Add a test called aWrongContentTypeNamesBothTypes to FailureMessagesTest. Expect ContentType.XML from GET /accounts, capture the failure, and check that the message starts with the count and contains doesn't match actual content-type "application/json.
Hint
Copy aWrongStatusCodeNamesExpectedAndActual, replace the status check with contentType(ContentType.XML), and add the io.restassured.http.ContentType import.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aWrongContentTypeNamesBothTypes() {
AssertionError error = assertThrows(AssertionError.class, () ->
accountsApi()
.when()
.get("/accounts")
.then()
.contentType(ContentType.XML));
String message = error.getMessage();
assertTrue(message.startsWith("1 expectation failed."), message);
assertTrue(message.contains("doesn't match actual content-type \"application/json"), message);
}
Exercise 2: Report Every Wrong Field of a GBP Account
Add a test called oneBodyCallReportsEveryWrongField to FailureMessagesTest. Request acc-1004, check that the status code is 200, then check in one body(..) call that the owner is "Emily Clarke", the currency is "EUR" and the type is "SAVINGS". Capture the failure, and check that it reports exactly the two wrong fields and doesn’t mention the owner.
Hint
Combine allPathsOfOneBodyCallAreReportedTogether with the assertFalse from aThenChainStopsAtTheFirstFailingCall. The status check holds, so the chain reaches the body(..) call.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void oneBodyCallReportsEveryWrongField() {
AssertionError error = assertThrows(AssertionError.class, () ->
accountsApi()
.when()
.get("/accounts/{id}", "acc-1004")
.then()
.statusCode(200)
.body("owner", equalTo("Emily Clarke"),
"currency", equalTo("EUR"),
"type", equalTo("SAVINGS")));
String message = error.getMessage();
assertTrue(message.startsWith("2 expectations failed."), message);
assertTrue(message.contains("JSON path currency doesn't match."), message);
assertTrue(message.contains("JSON path type doesn't match."), message);
assertFalse(message.contains("JSON path owner"), message);
}
Summary
You built FailureMessagesTest, which checks failure messages while the build stays green, and DeliberatelyFailingTest, which shows real red output on demand. You’ve finished Module 1: you can now write, point, check, log and debug a REST Assured test.
- A REST Assured failure is a plain
AssertionError, whose message starts with the number of failed expectations. - Each failure names what was checked, such as the JSON path, and shows the expected and actual values.
- After
then(), each call is checked at once, so a chain stops at its first failing call. - All path and matcher pairs in one
body(..)call are checked together, so one run reports every mismatch in it. - When the expected and actual values look the same, compare their types, such as
-42.1and-42.1F.
Here are the commands you used in this guide:
1
2
mvn test -pl module-01 -Dtest=FailureMessagesTest
mvn test -pl module-01 -Dtest=DeliberatelyFailingTest -DexcludedGroups=none
What’s Next
Next: you’ve completed Module 1. Continue with Module 2: Building Requests, which covers every way to put data into a request, starting with Fill Path Parameters in REST Assured.
The code:
- The finished test classes:
FailureMessagesTest.javaandDeliberatelyFailingTest.java - The code and run commands for this module: Module 1 README
Go deeper:
- JUnit User Guide: Tagging and Filtering, for how tags like
expected-failure-testswork. - REST Assured Usage wiki, for every verification method and its failure output.
Related guides:
- Check Every Part of an HTTP Response, for the checks whose failures this guide reads.
- Log REST Assured Requests and Responses, for the logging options that print next to a failure.
