Post

Shorten JSON Paths With Root Paths in REST Assured

Stop repeating the start of every path with rootPath, move it with appendRootPath, detachRootPath and noRootPath, and reuse one path for different values with withArgs.

Shorten JSON Paths With Root Paths in REST Assured

Your rent check reads transactions[2].id, transactions[2].category and transactions[2].counterparty.name. The part that matters is at the end of each path, and the start is repeated every time. When the data changes order, you edit the index in three places, and when you need the same check for three transactions, you copy the path three times. In this guide, you’ll write the start of a path once with a root path, and reuse one path for many values with path arguments.

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

What You’ll Build

You’ll build a test class called RootPathTest with four tests. Two set and move a root path through one transaction; two fill a %s placeholder in a path with different values.

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

{"accountId":"acc-1001","currency":"EUR","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:

  • Set a root path.
  • Move the root path.
  • Reuse a path with arguments.

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 RootPathTest in a new section_02 package next to the class from the previous section, and follow every heading below.
  • Skip ahead: open the finished class (RootPathTest.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 root paths in reusable response specifications; they’re taught in Module 5.

Understand Root Paths and Path Arguments

The problem. When several checks look at one object deep in a body, every path starts the same way. The repeated start hides what each check is about, and every change to it means several edits. A check repeated for different values has the same problem in another direction: the same path, copied with one value changed.

The concept. A root path is a prefix that REST Assured puts in front of every path in the body(..) calls that follow it. Four methods control it:

MethodEffect
rootPath(path)Sets the prefix
appendRootPath(path)Adds a step to the end of the current prefix
detachRootPath(path)Removes a step from the end of the current prefix
noRootPath()Removes the prefix, so paths start at the top of the body again

A path argument fills a %s placeholder in a path, or in a root path. You pass it with withArgs(..), between the path and the matcher. It works like String.format, once per body(..) call.

When to use each. Use no root path for a few checks spread across the body. Use rootPath(..) for several checks on one object, and appendRootPath(..) with detachRootPath(..) when the checks move into and out of a nested object. Use withArgs(..) when one path is checked for several values. A chain with five moves of the root path is hard to follow, so split it or write the full paths.

Write the start of a path once, and name what varies.

Meet the API Under Test

The tests use the Transactions API from the previous section, and the six transactions of account acc-1001. The account’s top-level fields include iban and currency, and the third transaction, transactions[2], is the rent:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{
    "accountId": "acc-1001",
    "iban": "NL91ABNA0417164300",
    "currency": "EUR",
    "transactions": [
        { "id": "tx-1", "category": "SALARY", "counterparty": { "name": "Acme B.V." }, ... },
        { "id": "tx-2", "category": "GROCERIES", "counterparty": { "name": "Albert Heijn" }, ... },
        {
            "id": "tx-3",
            "type": "DEBIT",
            "amount": -1100.00,
            "counterparty": { "iban": "NL27INGB0000123456", "name": "Woonstichting De Key" },
            "category": "RENT",
            ...
        },
        ...
    ]
}

Your tests check these fields:

  • id, category and counterparty.name of single transactions, read through a root path.
  • currency, a top-level field, read after the root path is cleared.

See Meet the API Under Test in the previous section for the full table of transactions.

Set a Root Path

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

import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.withArgs;
import static org.hamcrest.Matchers.equalTo;

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 RootPathTest {

    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 the ValidatableResponse, as in the previous section.
  • withArgs is a static import from io.restassured.RestAssured. You’ll use it for the path arguments.

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

Check One Transaction Through a Root Path

Goal: check three fields of the rent transaction, writing its index once.

1
2
3
4
5
6
7
8
@Test
void aRootPathPrefixesEveryPath() {
    transactions()
        .rootPath("transactions[2]")
        .body("id", equalTo("tx-3"))
        .body("category", equalTo("RENT"))
        .body("counterparty.name", equalTo("Woonstichting De Key"));
}

What’s happening:

  • rootPath("transactions[2]") sets the prefix for every body(..) call after it.
  • Each path is joined to the root path with a dot, so "id" is read as transactions[2].id.
  • The index now appears once. To check a different transaction, you change one line.

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

A failure message shows the full path, root path included. If the category were wrong, you’d see JSON path transactions[2].category doesn't match., so a root path never hides what was checked.

Move the Root Path

Move Into and Out of a Nested Object

Goal: move the root path into a transaction, into its counterparty, back out, and back to the top.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void movingTheRootPath() {
    transactions()
        .rootPath("transactions[0]")
        .body("id", equalTo("tx-1"))
        .appendRootPath("counterparty")
        .body("name", equalTo("Acme B.V."))
        .detachRootPath("counterparty")
        .body("category", equalTo("SALARY"))
        .noRootPath()
        .body("currency", equalTo("EUR"));
}

What’s happening:

Each call changes the root path for the checks that follow it:

CallRoot path afterwardsbody("x", ..) reads
rootPath("transactions[0]")transactions[0]transactions[0].x
appendRootPath("counterparty")transactions[0].counterpartytransactions[0].counterparty.x
detachRootPath("counterparty")transactions[0]transactions[0].x
noRootPath()nonex
  • The chain reads like moving through the body, ending at the account’s currency.

Checkpoint: run the class again. Two tests pass.

A root path stays until you change it. A check on a top-level field after a root path reads the wrong path and gets null: without noRootPath(), "currency" is read as transactions[0].currency. You’ll see that failure in Make a Test Fail.

Reuse a Path With Arguments

Fill a Placeholder With withArgs

Goal: check the category of three transactions with one path.

1
2
3
4
5
6
7
8
9
@Test
void pathArgumentsFillPlaceholders() {
    String categoryOfTransaction = "transactions.find { it.id == '%s' }.category";

    transactions()
        .body(categoryOfTransaction, withArgs("tx-1"), equalTo("SALARY"))
        .body(categoryOfTransaction, withArgs("tx-3"), equalTo("RENT"))
        .body(categoryOfTransaction, withArgs("tx-5"), equalTo("TRANSPORT"));
}

What’s happening:

  • The path is written once, in a variable whose name says what it reads.
  • withArgs(..) comes between the path and the matcher, and replaces %s before the path is evaluated.
  • The quotes around %s belong to the GPath string, so the id is compared as text.
  • A path can hold several placeholders, filled in order: withArgs("DEBIT", "GROCERIES") fills two.

Checkpoint: run the class again. Three tests pass.

Keep the quotes around %s for text values. Without them, it.id == %s becomes it.id == tx-1, which Groovy reads as tx minus 1, and REST Assured throws The parameter "tx" was used but not defined.

Put a Placeholder in the Root Path

Goal: find a transaction by id in the root path, and say which one in each check.

1
2
3
4
5
6
7
@Test
void aRootPathWithAPlaceholder() {
    transactions()
        .rootPath("transactions.find { it.id == '%s' }")
        .body("counterparty.name", withArgs("tx-2"), equalTo("Albert Heijn"))
        .body("counterparty.name", withArgs("tx-6"), equalTo("Belastingdienst"));
}

What’s happening:

  • The placeholder is in the root path, but the argument still goes in each body(..) call.
  • The root path describes which kind of element to look at, and each check says which one.
  • Unlike an index, find { it.id == '%s' } keeps working when the order of the transactions changes, which answers the reordering problem from the opening.

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

Run the Tests

Run the following command from the repository root:

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

You should see a result similar to the following:

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

Make a Test Fail

In movingTheRootPath, delete the .noRootPath() line and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   RootPathTest.movingTheRootPath:60 1 expectation failed.
JSON path transactions[0].currency doesn't match.
Expected: EUR
  Actual: null

The message shows the full path that was read: the root path transactions[0] is still in front of currency. A transaction has no currency field, so the value is null. When a check fails with Actual: null, look at the path in the message before you look at the data.

Put the .noRootPath() line back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
Actual: null and the path in the message starts with the root pathA top-level check comes after a root pathCall noRootPath() before it
Actual: null and the path in the message still shows '%s'The body(..) call has no withArgs(..)Pass one argument per %s
The parameter "tx" was used but not defined%s isn’t quoted, so the id is read as codeWrite '%s' for text values

Try It Yourself

Exercise 1: Check the Last Transaction

Add a test called theLastTransactionIsTheRefund. Set the root path to the last transaction with a negative index, and check its id, category and counterparty.name. Then clear the root path and check the account’s iban, "NL91ABNA0417164300".

Hint

Combine aRootPathPrefixesEveryPath with the noRootPath() step from movingTheRootPath. [-1] is the last element, as in the previous section.

Solution
1
2
3
4
5
6
7
8
9
10
@Test
void theLastTransactionIsTheRefund() {
    transactions()
        .rootPath("transactions[-1]")
        .body("id", equalTo("tx-6"))
        .body("category", equalTo("REFUND"))
        .body("counterparty.name", equalTo("Belastingdienst"))
        .noRootPath()
        .body("iban", equalTo("NL91ABNA0417164300"));
}

Exercise 2: Combine a Placeholder Root Path With Two Arguments

Add a test called theRentCounterpartyAndTheGroceries. Set the root path to a transaction found by id with %s, then append counterparty, and check the name and iban of tx-3: "Woonstichting De Key" and "NL27INGB0000123456". Then clear the root path, and check with one path and two arguments that the ids of the DEBIT transactions in GROCERIES are tx-2 and tx-4.

Hint

appendRootPath(..) works on a root path with a placeholder too; pass withArgs("tx-3") in each check. A closure can combine two conditions with &&.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void theRentCounterpartyAndTheGroceries() {
    transactions()
        .rootPath("transactions.find { it.id == '%s' }")
        .appendRootPath("counterparty")
        .body("name", withArgs("tx-3"), equalTo("Woonstichting De Key"))
        .body("iban", withArgs("tx-3"), equalTo("NL27INGB0000123456"))
        .noRootPath()
        .body("transactions.findAll { it.type == '%s' && it.category == '%s' }.id",
                withArgs("DEBIT", "GROCERIES"), contains("tx-2", "tx-4"));
}

Add import static org.hamcrest.Matchers.contains; to the class.

Summary

You built RootPathTest, which checks single transactions through a root path, moves it into and out of a nested object, and reuses one path for several values with arguments. The rent check names its transaction once, and survives a reorder.

  • rootPath(..) puts a prefix in front of every path in the body(..) calls that follow it.
  • appendRootPath(..) and detachRootPath(..) move the prefix one step at a time, and noRootPath() clears it.
  • withArgs(..) fills %s placeholders, in a path or in a root path, once per body(..) call.
  • Quote '%s' for text values, and pass one argument per placeholder.
  • Failure messages always show the full path, so neither technique makes a failure harder to read.

Here are the commands you used in this guide:

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

What’s Next

Next: continue with Check Money Exactly With BigDecimal in REST Assured, which reads amounts as BigDecimal instead of Float.

The code:

Go deeper:

Related guides:

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