Post

Check Server-Generated Values With Response-Aware Matchers

Check values the server chooses by building the expectation from the response, covering a Location header that must end with the new id, endsWithPath(..), one body value checked against another, and a matcher on the whole body.

Check Server-Generated Values With Response-Aware Matchers

When you add a transaction, the server picks its id, and returns it twice: in the body and at the end of the Location header. Your test checks the header with endsWith("tx-7"), and it passes, until it runs after another test and the new id is tx-8. In this guide, you’ll build the expectation from the response itself, so a test can check values it can’t know in advance.

Level: Intermediate · Time: 15 minutes · Part of: Module 3: Validating Responses in Depth, section 5

What You’ll Build

You’ll build a test class called ResponseAwareMatcherTest with four tests. Each one adds a transaction and checks the response: two compare the Location header with the new id, one checks a rule between two body values, and one checks the whole body as text.

All four tests send this request and check this response:

1
2
3
4
5
6
7
8
9
10
POST /api/v1/accounts/acc-1001/transactions HTTP/1.1
Host: localhost:<port>
Content-Type: application/json

{"amount":-3.5,"counterpartyName":"Bakkerij Bart"}

HTTP/1.1 201 Created
Location: /api/v1/accounts/acc-1001/transactions/tx-7

{"id":"tx-7","type":"DEBIT","amount":-3.50,"counterparty":{"name":"Bakkerij Bart", ...}, ...}

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 a value the server generates.
  • Check one body value against another.
  • Check the whole body.

What You Need

How to Complete This Guide

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

  • Build it step by step: create ResponseAwareMatcherTest in a new section_05 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (ResponseAwareMatcherTest.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 using a generated value in a later request; that needs extract(), taught in Module 4.

Understand Response-Aware Matchers

The problem. A plain matcher is built before the request is sent, so it can only expect values the test already knows. A value the server generates, such as a new id, isn’t known until the response arrives. Hard-coding it ties the test to the order in which tests run; extracting it first and checking it in a second step works, but takes more code than the check deserves.

The concept. A response-aware matcher is a function that takes the response and returns a matcher. REST Assured calls it with the actual response, then checks the value with the matcher it returned. ResponseAwareMatcher is a functional interface, so a lambda is enough:

1
.header("Location", response -> endsWith("/transactions/" + response.path("id")))
  • response is the whole response, so response.path(..), response.header(..) and the other methods can read any part of it.
  • The lambda returns a matcher, here endsWith(..), built from what it read.
  • REST Assured applies that matcher to the value being checked, here the Location header.

header(..) and body(..) accept a response-aware matcher wherever they accept a normal one.

When to use it. Use one when a generated value appears twice, such as an id in the body and in a header, or when two values must agree by a rule, such as a type and the sign of an amount. Don’t use one for values you know: a plain matcher with the expected value is clearer. And keep the rule simple, because a matcher that repeats the server’s logic in detail also repeats its bugs.

Expect what the server promises, built from what it returned.

Meet the API Under Test

This guide uses one endpoint of the Transactions API:

MethodPathPurpose
POST/accounts/{id}/transactionsAdd a transaction to account acc-1001

It takes an amount and a counterpartyName, both required, and answers 201 Created:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
HTTP/1.1 201 Created
Content-type: application/json; charset=utf-8
Location: /api/v1/accounts/acc-1001/transactions/tx-7

{
    "id": "tx-7",
    "bookingDate": "2026-11-21",
    "type": "DEBIT",
    "amount": -3.50,
    "counterparty": { "name": "Bakkerij Bart", "iban": "NL00TEST0000000000" },
    "category": "OTHER",
    "tags": [],
    "remittance-info": "Added by a test"
}

Your tests check these values:

  • The id, the next free number after the six seeded transactions. It depends on what the class has already created.
  • The Location header, which must end with the same id.
  • The type, which the server chooses from the sign of the amount: DEBIT for a negative amount, CREDIT otherwise.

Without both fields, the API answers 422 with the field amount/counterpartyName.

Check a Value the Server Generates

Set Up the Test Class

Goal: create the test class with a helper that builds the request to add a transaction.

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
package com.javanibble.module_03.section_05;

import static io.restassured.RestAssured.given;
import static io.restassured.matcher.RestAssuredMatchers.endsWithPath;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;

import com.javanibble.transactions.TransactionsApi;

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

import java.util.Map;

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

class ResponseAwareMatcherTest {

    private static TransactionsApi api;

    @BeforeAll
    static void startApi() {
        api = TransactionsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification newTransaction() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(TransactionsApi.BASE_PATH)
            .contentType(ContentType.JSON)
            .body(Map.of("amount", -3.5, "counterpartyName", "Bakkerij Bart"));
    }
}

What’s happening:

  • newTransaction() returns a request with a JSON body for a small debit, so every test adds the same kind of transaction.
  • endsWithPath comes from io.restassured.matcher.RestAssuredMatchers, REST Assured’s own matchers.

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

These tests change the data, so it matters that every test class starts its own API in @BeforeAll. The transactions added here never show up in the classes that check exact totals.

Build the Expectation From the Body

Goal: check that the Location header ends with the id in the body, whatever it is.

1
2
3
4
5
6
7
8
9
@Test
void theLocationHeaderEndsWithTheNewId() {
    newTransaction()
    .when()
        .post("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
    .then()
        .statusCode(201)
        .header("Location", response -> endsWith("/transactions/" + response.path("id")));
}

What’s happening:

  • The lambda reads the id from the body, such as tx-7, and returns endsWith("/transactions/tx-7").
  • REST Assured checks the Location header with that matcher.
  • The test works whatever id the server picks, so it passes in any order.

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

Don’t hard-code a generated id. header("Location", endsWith("tx-7")) passes only when the test runs first. Run after another test, it fails with Expected header "Location" was not a string ending with "tx-7", was "/api/v1/accounts/acc-1001/transactions/tx-8".

Use the Ready-Made endsWithPath(..)

Goal: write the same check with a matcher REST Assured provides.

1
2
3
4
5
6
7
8
@Test
void readyMadeResponseAwareMatchers() {
    newTransaction()
    .when()
        .post("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
    .then()
        .header("Location", endsWithPath("id"));
}

What’s happening:

  • endsWithPath("id") reads the value at the path id and checks that the header ends with it.
  • It’s the same check as the lambda in the previous step, in one call.
  • RestAssuredMatchers also has equalToPath(..), startsWithPath(..) and containsPath(..).

Checkpoint: run the class again. Two tests pass.

Check One Body Value Against Another

Check a Rule Between Two Values

Goal: check that the type agrees with the sign of the amount, without hard-coding the type.

1
2
3
4
5
6
7
8
@Test
void aBodyValueCheckedAgainstAnotherBodyValue() {
    newTransaction()
    .when()
        .post("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
    .then()
        .body("type", response -> equalTo(response.<Float>path("amount") < 0 ? "DEBIT" : "CREDIT"));
}

What’s happening:

  • The test states the rule: a negative amount is a DEBIT, anything else a CREDIT. If the helper sent a positive amount, the same test would expect CREDIT.
  • response.<Float>path("amount") reads the amount with a type witness, so the comparison with 0 compiles. The amount is a Float, the default for decimals.
  • The rule is one line. Keep it that simple, so the test checks the server rather than repeating it.

Checkpoint: run the class again. Three tests pass.

path(..) is generic, so it needs a type witness before a comparison. Without one, response.path("amount") < 0 doesn’t compile: bad operand types for binary operator '<'. And the witness must match the actual type: the server always sends two decimals, so even 25 comes back as 25.00, and <Integer> throws ClassCastException: class java.lang.Float cannot be cast to class java.lang.Integer.

Check the Whole Body

Match the Body as Text

Goal: check that a value appears somewhere in the body.

1
2
3
4
5
6
7
8
@Test
void theWholeBody() {
    newTransaction()
    .when()
        .post("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
    .then()
        .body(containsString("Bakkerij Bart"));
}

What’s happening:

  • body(..) without a path applies the matcher to the whole body as a string.
  • It’s a quick check that a value appears somewhere, but it doesn’t say where.

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

Prefer a path when you know one. body(containsString("Bakkerij Bart")) passes when the name appears in the wrong field; body("counterparty.name", equalTo("Bakkerij Bart")) doesn’t.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-03 -Dtest=ResponseAwareMatcherTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_03.section_05.ResponseAwareMatcherTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.408 s -- in com.javanibble.module_03.section_05.ResponseAwareMatcherTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

None of the tests assumes an id, so they pass in any order.

Make a Test Fail

In theLocationHeaderEndsWithTheNewId, change "/transactions/" to "/payments/" in the lambda and run the command again. You should see a result similar to the following:

1
2
3
4
5
6
[ERROR] Failures:
[ERROR]   ResponseAwareMatcherTest.theLocationHeaderEndsWithTheNewId:54 1 expectation failed.
Expected header "Location" was not a string ending with "/payments/tx-10", was "/api/v1/accounts/acc-1001/transactions/tx-10". Headers are:
Content-type=application/json; charset=utf-8
Location=/api/v1/accounts/acc-1001/transactions/tx-10
...

The message shows the matcher the lambda built, with the real id already filled in, next to the actual header. The id may differ on your run, because it depends on which tests ran first; that’s exactly why the test reads it from the response.

Change "/payments/" back to "/transactions/" and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
Expected header "Location" was not a string ending with "tx-7", was ".../tx-8"The test hard-codes a generated idBuild the expectation from the response
bad operand types for binary operator '<' when compilingresponse.path(..) has no type witnessWrite response.<Float>path("amount")
ClassCastException: class java.lang.Float cannot be cast to class java.lang.IntegerThe type witness doesn’t match the value’s typeUse <Float> for decimals
422 with "field": "amount/counterpartyName"The request body is missing a fieldSend both amount and counterpartyName

Try It Yourself

Exercise 1: Check the Rule for a Credit

Add a test called aPositiveAmountIsACredit that adds a transaction of 25 from "Oma". Check the status code, the type with the same rule as aBodyValueCheckedAgainstAnotherBodyValue, and that the type is "CREDIT".

Hint

Build the request with given() instead of newTransaction(), with your own body. The server sends 25.00, so the type witness is still <Float>.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aPositiveAmountIsACredit() {
    given().baseUri(api.baseUri()).port(api.port()).basePath(TransactionsApi.BASE_PATH)
        .contentType(ContentType.JSON)
        .body(Map.of("amount", 25, "counterpartyName", "Oma"))
    .when()
        .post("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
    .then()
        .statusCode(201)
        .body("type", response -> equalTo(response.<Float>path("amount") < 0 ? "DEBIT" : "CREDIT"))
        .body("type", equalTo("CREDIT"));
}

Exercise 2: Check a New Transaction in Full

Add a test called aNewTransactionIsConsistent. Add a transaction with newTransaction(), and check in one chain: the status code; that the Location header starts with /api/v1/accounts/acc-1001/transactions/ and ends with the id; that the id matches tx- followed by digits; that the counterparty name is "Bakkerij Bart"; and that the amount is -3.5.

Hint

Combine startsWith(..) with endsWithPath("id") in two header(..) checks, and matchesPattern(..) from Pick the Right Hamcrest Matcher in REST Assured. The amount is a Float.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aNewTransactionIsConsistent() {
    newTransaction()
    .when()
        .post("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
    .then()
        .statusCode(201)
        .header("Location", startsWith("/api/v1/accounts/acc-1001/transactions/"))
        .header("Location", endsWithPath("id"))
        .body("id", matchesPattern("tx-[0-9]+"))
        .body("counterparty.name", equalTo("Bakkerij Bart"))
        .body("amount", equalTo(-3.5f));
}

Add import static org.hamcrest.Matchers.matchesPattern; and import static org.hamcrest.Matchers.startsWith; to the class.

Summary

You built ResponseAwareMatcherTest, which checks a new transaction’s Location header against its generated id, checks the type against the sign of the amount, and checks the whole body as text. The test no longer cares whether the new id is tx-7 or tx-8.

  • A response-aware matcher is a lambda from the response to a matcher, accepted wherever header(..) or body(..) accepts a matcher.
  • Use it for values the server generates, such as an id that appears in the body and the Location header.
  • RestAssuredMatchers has ready-made ones, such as endsWithPath(..) and equalToPath(..).
  • Read values with a type witness that matches their type, such as response.<Float>path("amount"), and keep the rule simple.
  • body(..) without a path matches the whole body as text; prefer a path when you know one.

Here are the commands you used in this guide:

1
mvn test -pl module-03 -Dtest=ResponseAwareMatcherTest

What’s Next

Next: continue with Check Session Cookie Security in REST Assured, which checks the cookies a server sets, down to the security attributes of a session cookie.

The code:

Go deeper:

Related guides:

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