Pick the Right Hamcrest Matcher in REST Assured
Pick the right Hamcrest matcher for each check, covering hasItems, contains and containsInAnyOrder, everyItem and empty, hasKey and hasEntry, string matchers, and combining matchers with allOf, anyOf, oneOf and not.
Your transaction test checks the ids with hasItems(..), and it passes the day the API starts returning a duplicate transaction. A colleague’s test uses contains(..), and it fails the day the API sorts by amount instead of date, though nobody relies on the order. In this guide, you’ll pick the Hamcrest matcher that says exactly what the API promises, for lists, objects and strings, and combine matchers when one isn’t enough.
Level: Intermediate · Time: 20 minutes · Part of: Module 3: Validating Responses in Depth, section 4
What You’ll Build
You’ll build a test class called HamcrestToolboxTest with four tests, one per group of matchers: collections, maps, strings and combinations. All of them check the same month of transactions.
All four tests send this request and check this response:
1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1001/transactions HTTP/1.1
Host: localhost:<port>
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{"iban":"NL91ABNA0417164300","currency":"EUR","balance":{...},"transactions":[{"id":"tx-1", ...}, ...]}
When you’re done, Maven reports four passing tests:
1
2
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Check collections.
- Check objects as maps.
- Check strings.
- Combine matchers.
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 filter and slice lists with GPath, as taught in Filter JSON Lists With GPath in REST Assured, and you’ve used
equalTo(..),hasItems(..)andcontains(..)in earlier guides.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
HamcrestToolboxTestin a newsection_04package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
HamcrestToolboxTest.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 Filter JSON Lists With GPath in REST Assured.
Out of scope: this guide doesn’t cover matchers that compare one part of the response with another, or writing your own matchers; they’re taught in section 5 and the Hamcrest tutorial.
Understand Hamcrest Matchers
The problem. Several matchers can make the same test pass today and still mean different things. One says “at least these”, another “exactly these, in this order”. A matcher that’s too weak lets a bug through, such as an extra transaction; one that’s too strict fails on a change nobody cares about, such as a new sort order.
The concept. A matcher is an object that checks a value and describes what it expected. REST Assured passes the value at a path to the matcher, and when the matcher fails, it uses that description in the failure message. All the matchers here are static methods of org.hamcrest.Matchers, which comes with REST Assured. They fall into four groups:
| Group | Matchers |
|---|---|
| Collections | hasSize, hasItem, hasItems, contains, containsInAnyOrder, everyItem, empty |
| Maps | hasKey, hasEntry, hasValue |
| Strings | startsWith, containsString, matchesPattern, equalToIgnoringCase |
| Combinations | allOf, anyOf, oneOf, not |
When to use each. Pick the weakest matcher that still says what the API promises. If the API returns transactions by date, contains(..) checks that. If it only promises that the rent is among them, hasItem(..) is enough, and the test won’t break when a new transaction is added. When you know a value’s exact format, check it exactly rather than in part.
Choose the matcher for what the API promises, no more and no less.
Meet the API Under Test
The tests use the Transactions API and account acc-1001 from Filter JSON Lists With GPath in REST Assured. The fields that matter here, shortened:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{
"accountId": "acc-1001",
"iban": "NL91ABNA0417164300",
"currency": "EUR",
"balance": { "opening": 1000.00, "closing": 2407.65 },
"transactions": [
{
"id": "tx-1",
"type": "CREDIT",
"counterparty": { "iban": "NL02ABNA0123456789", "name": "Acme B.V." },
"category": "SALARY",
"remittance-info": "Salary March",
...
},
...
]
}
Your tests check these fields:
transactions.idandtransactions.category: six transactions,tx-1totx-6, in the categoriesSALARY,GROCERIES,RENT,TRANSPORTandREFUND.balance, an object withopeningandclosing, and noavailable.ibanandcurrency, the account’s top-level strings.
Check Collections
Set Up the Test Class
Goal: create the test class, start the Transactions API and add a helper that returns the checked response.
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
package com.javanibble.module_03.section_04;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.oneOf;
import static org.hamcrest.Matchers.startsWith;
import com.javanibble.transactions.TransactionsApi;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class HamcrestToolboxTest {
private static TransactionsApi api;
@BeforeAll
static void startApi() {
api = TransactionsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static ValidatableResponse transactions() {
return given().baseUri(api.baseUri()).port(api.port()).basePath(TransactionsApi.BASE_PATH)
.when().get("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
.then();
}
}
What’s happening:
transactions()sends the request and returns theValidatableResponse, as in the previous sections.- The static imports are every matcher this guide uses. Your IDE may mark some as unused until you add the tests that need them.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Check Lists With the Collection Matchers
Goal: check the transaction list for size, membership, order and a rule for every element.
1
2
3
4
5
6
7
8
9
10
11
@Test
void collections() {
transactions()
.body("transactions.id", hasSize(6))
.body("transactions.category", hasItem("RENT"))
.body("transactions.category", hasItems("RENT", "SALARY"))
.body("transactions[0..2].id", contains("tx-1", "tx-2", "tx-3"))
.body("transactions[0..2].id", containsInAnyOrder("tx-3", "tx-1", "tx-2"))
.body("transactions.id", everyItem(startsWith("tx-")))
.body("transactions.findAll { it.category == 'GAMBLING' }", empty());
}
What’s happening:
hasSize(6)checks the number of elements.hasItem(..)andhasItems(..)check that the list contains at least these values.contains(..)checks exactly these values in this order, andcontainsInAnyOrder(..)exactly these values in any order.everyItem(..)applies a matcher to every element, andempty()checks for an empty list, here afindAllthat should find nothing.
The three list matchers that are easiest to confuse differ in two ways:
| Matcher | Extra items | Order |
|---|---|---|
hasItems("a", "b") | Allowed | Doesn’t matter |
containsInAnyOrder("a", "b") | Not allowed | Doesn’t matter |
contains("a", "b") | Not allowed | Must match |
Checkpoint: run HamcrestToolboxTest from your IDE. One test runs and passes.
Don’t use
contains(..)when you mean “at least”.contains("tx-1", "tx-2")fails on the full list of six ids withExpected: iterable containing ["tx-1", "tx-2"]. AndhasItems(..)passes when the API returns extra, unexpected items, so usecontainsInAnyOrder(..)when you mean “exactly”.
everyItem(..)passes on an empty list, because no element breaks the rule. Pair it withhasSize(..)ornot(empty())when the list must have elements.
Check Objects as Maps
Check Keys and Entries
Goal: check that a field exists, that it has a value, and that another field is absent.
A JSON object is a map, so map matchers work on it:
1
2
3
4
5
6
7
@Test
void maps() {
transactions()
.body("transactions[0]", hasKey("remittance-info"))
.body("transactions[0].counterparty", hasEntry("name", "Acme B.V."))
.body("balance", not(hasKey("available")));
}
What’s happening:
hasKey(..)checks that a field exists, whatever its value.hasEntry(key, value)checks a field and its value together.not(hasKey(..))checks that a field is absent.
Checkpoint: run the class again. Two tests pass.
Don’t use
nullValue()to check that a field is absent.body("balance.available", nullValue())passes here, but it would also pass if the field existed with the valuenull. Usenot(hasKey(..))on the parent object when the difference matters.
Check Strings
Check Part or All of a Value
Goal: check the account’s IBAN by prefix, by part, by format and without case.
1
2
3
4
5
6
7
8
@Test
void strings() {
transactions()
.body("iban", startsWith("NL"))
.body("iban", containsString("ABNA"))
.body("iban", matchesPattern("[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}"))
.body("iban", equalToIgnoringCase("nl91abna0417164300"));
}
What’s happening:
startsWith(..)andcontainsString(..)check part of a value.matchesPattern(..)checks the format with a regular expression. It’s the right check for values the server generates, such as ids, timestamps and IBANs.equalToIgnoringCase(..)ignores upper and lower case.
Checkpoint: run the class again. Three tests pass.
matchesPattern(..)must match the whole value, not part of it.matchesPattern("NL")fails onNL91ABNA0417164300withExpected: a string matching the pattern 'NL'. UsestartsWith(..)for a prefix.
Don’t use
containsString(..)on a value you could check exactly. It hides wrong values that happen to contain the text. UseequalTo(..)ormatchesPattern(..)when you know the format.
Combine Matchers
Use allOf, anyOf, oneOf and not
Goal: express rules that need more than one matcher.
1
2
3
4
5
6
7
8
@Test
void combiningMatchers() {
transactions()
.body("balance", allOf(hasKey("opening"), hasKey("closing")))
.body("currency", anyOf(equalTo("EUR"), equalTo("GBP")))
.body("transactions.category", everyItem(oneOf("SALARY", "GROCERIES", "RENT", "TRANSPORT", "REFUND")))
.body("transactions.type", not(hasItem("PENDING")));
}
What’s happening:
allOf(..)passes when every matcher passes, andanyOf(..)when at least one does.oneOf(..)passes when the value equals one of the given values. InsideeveryItem(..), it checks that every category is a known one.not(..)inverts a matcher: no transaction isPENDING.
Checkpoint: run the class again. All four tests pass.
allOf(..)is most useful inside a matcher that takes one matcher, such aseveryItem(..). In athen()chain, two separatebody(..)calls do the same job and give two clearer failure messages.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-03 -Dtest=HamcrestToolboxTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_03.section_04.HamcrestToolboxTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.465 s -- in com.javanibble.module_03.section_04.HamcrestToolboxTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In collections, change contains("tx-1", "tx-2", "tx-3") to contains("tx-2", "tx-1", "tx-3") and run the command again. You should see a result similar to the following:
1
2
3
4
5
[ERROR] Failures:
[ERROR] HamcrestToolboxTest.collections:63 1 expectation failed.
JSON path transactions[0..2].id doesn't match.
Expected: iterable containing ["tx-2", "tx-1", "tx-3"]
Actual: <[tx-1, tx-2, tx-3]>
The same three ids are there, but contains(..) requires this order, and the failure shows both lists side by side. If the order doesn’t matter to the API, that’s the sign to use containsInAnyOrder(..), which passes on the same data.
Change the order back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Expected: iterable containing [..] with a longer Actual list | contains(..) expects exactly these items | Use hasItems(..) for “at least these” |
Expected: iterable with items [..] in any order with a longer Actual list | containsInAnyOrder(..) doesn’t allow extra items | List every item, or use hasItems(..) |
Expected: a string matching the pattern '..' for a value that contains it | matchesPattern(..) must match the whole value | Extend the pattern, or use startsWith(..) or containsString(..) |
An everyItem(..) check passes though the list should have elements | everyItem(..) passes on an empty list | Add hasSize(..) or not(empty()) |
Try It Yourself
Exercise 1: Check the Credits and Debits
Add a test called creditsAndDebits that checks two things: the counterparty names of the credits are exactly "Belastingdienst" and "Acme B.V.", in any order; and the debit categories include at least "RENT" and "TRANSPORT".
Hint
Filter with findAll { it.type == '..' } and walk into the field you need. Pick one matcher for “exactly, any order” and one for “at least” from the table.
Solution
1
2
3
4
5
6
7
@Test
void creditsAndDebits() {
transactions()
.body("transactions.findAll { it.type == 'CREDIT' }.counterparty.name",
containsInAnyOrder("Belastingdienst", "Acme B.V."))
.body("transactions.findAll { it.type == 'DEBIT' }.category", hasItems("RENT", "TRANSPORT"));
}
Exercise 2: Check the Shape of Every Transaction
Add a test called everyTransactionHasTheRightShape that checks, in one chain: the list isn’t empty; every transaction has the keys id, amount and counterparty; every booking date matches 2026-03- followed by two digits; every counterparty IBAN matches the IBAN pattern from strings; and every type is DEBIT or CREDIT.
Hint
Guard the everyItem(..) checks with not(empty()), as the warning explains. everyItem(..) takes one matcher, so combine the three key checks with allOf(..).
Solution
1
2
3
4
5
6
7
8
9
@Test
void everyTransactionHasTheRightShape() {
transactions()
.body("transactions", not(empty()))
.body("transactions", everyItem(allOf(hasKey("id"), hasKey("amount"), hasKey("counterparty"))))
.body("transactions.bookingDate", everyItem(matchesPattern("2026-03-[0-9]{2}")))
.body("transactions.counterparty.iban", everyItem(matchesPattern("[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}")))
.body("transactions.type", everyItem(oneOf("DEBIT", "CREDIT")));
}
Summary
You built HamcrestToolboxTest, which checks lists, objects and strings with the matcher that says what the API promises, and combines matchers for rules that need more than one. A duplicate transaction or a harmless new sort order no longer fools your tests.
hasItems(..)means at least these,containsInAnyOrder(..)exactly these in any order, andcontains(..)exactly these in this order.everyItem(..)andempty()check a whole list;everyItem(..)passes on an empty list, so check the size too.hasKey(..)andhasEntry(..)check objects, andnot(hasKey(..))checks that a field is absent.matchesPattern(..)checks the whole value against a regular expression, and suits values the server generates.- Combine matchers with
allOf(..),anyOf(..),oneOf(..)andnot(..); the right choice makes both the test and its failure message clear.
Here are the commands you used in this guide:
1
mvn test -pl module-03 -Dtest=HamcrestToolboxTest
What’s Next
Next: continue with Check Server-Generated Values With Response-Aware Matchers, which checks values the server chooses by building the expectation from the response itself.
The code:
- The finished test class:
HamcrestToolboxTest.java - The code and run commands for this module: Module 3 README
Go deeper:
- Hamcrest Matchers javadoc, for the full list of matchers.
- Hamcrest tutorial, for how matchers work and how to write your own.
Related guides:
- Filter JSON Lists With GPath in REST Assured, for the paths these matchers check.
- Check Money Exactly With BigDecimal in REST Assured, for
comparesEqualTo(..)andcloseTo(..).
