Post

Map Responses to Java Records in REST Assured

Turn response bodies into Java records with as(..), send a record and get one back, map generic types such as Page and List with TypeRef, see why unknown fields don't break a test, and assert on records with AssertJ.

Map Responses to Java Records in REST Assured

Your account tests read seven fields through seven string paths, and a typo such as "segmnet" only shows up when the test runs, as a null. A page of customers multiplies the paths again. In this guide, you’ll describe the API’s JSON once, as Java records, and let REST Assured turn each response body into one, so the compiler checks every field name you use and your IDE completes them.

Level: Intermediate · Time: 20 minutes · Part of: Module 4: Extracting Values and Mapping Objects, section 3

What You’ll Build

You’ll build a test class called ObjectMappingTest with five tests. They map a customer, a created customer, a generic page of customers and a list of accounts to records, and show that fields the records don’t have are ignored.

Two of the tests send this request and map this response to a List<Account>:

1
2
3
4
5
6
7
8
GET /api/v1/accounts HTTP/1.1
Host: localhost:<port>
Consent-ID: consent-1

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

[{"accountId":"acc-1001","iban":"NL11BANK0000000001","type":"CURRENT", ...},{"accountId":"acc-1002", ...}]

When you’re done, Maven reports five passing tests:

1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Map a body to a record.
  • Map generic types with a TypeRef.
  • Handle fields the record doesn’t match.

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 ObjectMappingTest in a new section_03 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (ObjectMappingTest.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 Extract Values From a Response in REST Assured.

Out of scope: this guide doesn’t cover choosing or configuring the object mapper, such as making it strict about unknown fields; that’s taught in section 4.

Understand Object Mapping

The problem. A path per field works for a few values. A customer has five fields, an account seven, and a page of customers holds several of each. Reading them one string path at a time makes long tests, and the compiler can’t tell you when a path is misspelled.

The concept. extract().as(type) reads the response body with an object mapper and returns an instance of the type:

  • REST Assured picks the mapper from the classpath and the content type. This module has Jackson 3, so JSON is read by Jackson 3.
  • Jackson matches JSON fields to record components by name, and converts each value to the component’s type, such as an ISO 8601 string to an Instant.
  • A generic type such as List<Account> needs a TypeRef, because Java erases the type argument at runtime.

The tests describe the API’s JSON with their own records, in the module’s Models class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public record NewCustomer(String name, String email, String segment) {
}

public record Customer(String id, String name, String email, String segment, Instant createdAt) {
}

public record Page<T>(List<T> items, int page, int size, int totalItems, int totalPages) {
}

public record NewConsent(String customerId, List<String> permissions) {
}

public record Link(String href) {
}

public record Consent(String consentId, String customerId, List<String> permissions, String status,
                      @JsonProperty("_links") Map<String, Link> links) {
}

public record Account(String accountId, String iban, String currency, String type, String nickname) {
}

When to use it. Map to a record when a test reads several fields of an object, or a list of objects. For one value, a path or body(..) is simpler. Write the records from the API’s contract, not by copying the API’s own classes: if the tests reused them, a renamed field would change both sides at once, and no test would notice.

Describe the contract as records, and let the compiler check every field you read.

Meet the API Under Test

This guide uses three parts of the Customers and Consents API:

MethodPathPurpose
GET/customers/{id}, /customersOne customer, or a page of customers
POST/customersCreate a customer
POST/consents, /consents/{id}/authorisationCreate a consent, then authorise it
GET/accountsThe customer’s accounts; needs an authorised Consent-ID

A new consent looks like this. Its _links field holds the link to authorise it:

1
2
3
4
5
6
7
8
9
10
11
{
    "consentId": "consent-1",
    "customerId": "cust-1",
    "permissions": ["ReadAccountsBasic"],
    "status": "AWAITING_AUTHORISATION",
    "expiresOn": "2027-02-19",
    "_links": {
        "self": { "href": "/api/v1/consents/consent-1" },
        "authorise": { "href": "/api/v1/consents/consent-1/authorisation" }
    }
}

With an authorised consent for cust-1, GET /api/v1/accounts returns a JSON array:

1
2
3
4
5
6
7
8
9
10
[
    {
        "accountId": "acc-1001", "iban": "NL11BANK0000000001", "currency": "EUR", "type": "CURRENT",
        "nickname": "Main account", "productCode": "CUR-01", "balance": "15000.00"
    },
    {
        "accountId": "acc-1002", "iban": "NL12BANK0000000002", "currency": "EUR", "type": "SAVINGS",
        "nickname": "Rainy day", "productCode": "SAV-01", "balance": "1250.50"
    }
]

Your tests check these fields:

  • The customer’s name, segment, email and createdAt.
  • The page’s totalItems and items.
  • Each account’s type and iban. The Account record deliberately leaves out productCode and balance, which the API also sends.

Map a Body to a Record

Set Up the Test Class

Goal: create the test class with a request helper, and a helper that creates and authorises a consent.

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
53
54
55
package com.javanibble.module_04.section_03;

import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;

import com.javanibble.consents.ConsentsApi;
import com.javanibble.module_04.support.Models.Account;
import com.javanibble.module_04.support.Models.Consent;
import com.javanibble.module_04.support.Models.Customer;
import com.javanibble.module_04.support.Models.NewConsent;
import com.javanibble.module_04.support.Models.NewCustomer;
import com.javanibble.module_04.support.Models.Page;

import io.restassured.common.mapper.TypeRef;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;

import java.time.Instant;
import java.util.List;

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

class ObjectMappingTest {

    private static ConsentsApi api;

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

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

    private static RequestSpecification consentsApi() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(ConsentsApi.BASE_PATH);
    }

    private static String authorisedConsent(String customerId, List<String> permissions) {
        Consent consent = consentsApi()
            .contentType(ContentType.JSON)
            .body(new NewConsent(customerId, permissions))
            .when().post("/consents")
            .then().statusCode(201)
            .extract().as(Consent.class);

        consentsApi().when().post(consent.links().get("authorise").href().substring(ConsentsApi.BASE_PATH.length()))
            .then().statusCode(200);
        return consent.consentId();
    }
}

What’s happening:

  • authorisedConsent(..) creates a consent, maps the response to a Consent record, and follows its authorise link to authorise it. The account tests need its id.
  • consent.links().get("authorise").href() reads the link through the record, with no string path.
  • TypeRef comes from io.restassured.common.mapper; you’ll use it for generic types.

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

Map One Customer

Goal: map a customer to a record, and read its fields as typed values.

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aRecord() {
    Customer customer = consentsApi()
    .when()
        .get("/customers/{id}", "cust-3")
    .then()
        .statusCode(200)
        .extract().as(Customer.class);

    assertThat(customer.name()).isEqualTo("Bakkerij Bart B.V.");
    assertThat(customer.segment()).isEqualTo("BUSINESS");
    assertThat(customer.createdAt()).isBefore(Instant.now());
}

What’s happening:

  • extract().as(Customer.class) maps the whole body to a Customer record, after the status check.
  • customer.name() is a method call, so a misspelled field name doesn’t compile.
  • createdAt arrives as an ISO 8601 string, and Jackson 3 turns it into an Instant without an extra module, so the test compares dates instead of strings.

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

Send a Record and Get One Back

Goal: create a customer from a record, and map the response to another.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void aRecordInAndARecordOut() {
    NewCustomer request = new NewCustomer("Sanne Smit", "sanne@example.nl", "RETAIL");

    Customer created = consentsApi()
        .contentType(ContentType.JSON)
        .body(request)
    .when()
        .post("/customers")
    .then()
        .statusCode(201)
        .extract().as(Customer.class);

    assertThat(created)
        .returns("Sanne Smit", Customer::name)
        .returns("sanne@example.nl", Customer::email);
    assertThat(created.id()).startsWith("cust-");
}

What’s happening:

  • The same mapper writes the request body and reads the response.
  • AssertJ’s returns(expected, getter) checks several components of one record in a single statement.
  • The id is generated, so the test checks its format with startsWith("cust-").

Checkpoint: run the class again. Two tests pass.

Map Generic Types With a TypeRef

Map a Page of Customers

Goal: map a generic Page<Customer>.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aGenericPageNeedsATypeRef() {
    Page<Customer> page = consentsApi()
        .queryParam("size", 2)
    .when()
        .get("/customers")
    .then()
        .extract().as(new TypeRef<Page<Customer>>() {});

    assertThat(page.totalItems()).isGreaterThanOrEqualTo(5);
    assertThat(page.items()).hasSize(2).allSatisfy(customer -> assertThat(customer.id()).startsWith("cust-"));
}

What’s happening:

  • Page<Customer>.class doesn’t exist in Java. At runtime there’s only Page, and Jackson can’t know that items holds customers.
  • new TypeRef<Page<Customer>>() {} is an anonymous subclass, and a subclass keeps its type argument, so Jackson can read it.
  • isGreaterThanOrEqualTo(5) allows for customers that other tests create on the same server.
  • allSatisfy(..) runs the same assertion on every element, and reports each one that fails.

Checkpoint: run the class again. Three tests pass.

Don’t map a generic type without a TypeRef. as(Page.class) compiles, but the items are LinkedHashMaps, and the first one you read as a Customer throws ClassCastException: class java.util.LinkedHashMap cannot be cast to class ...Models$Customer. And keep the {}: new TypeRef<List<Account>>() doesn’t compile, because TypeRef is abstract; cannot be instantiated.

Map a JSON Array to a List

Goal: map the accounts array to a List<Account>, and check every account.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void aJsonArrayAsAList() {
    String consentId = authorisedConsent("cust-1", List.of("ReadAccountsBasic"));

    List<Account> accounts = consentsApi()
        .header("Consent-ID", consentId)
    .when()
        .get("/accounts")
    .then()
        .statusCode(200)
        .extract().as(new TypeRef<List<Account>>() {});

    assertThat(accounts)
        .extracting(Account::type)
        .containsExactly("CURRENT", "SAVINGS");
    assertThat(accounts).allSatisfy(account -> assertThat(account.iban()).matches("NL\\d{2}BANK\\d{10}"));
}

What’s happening:

  • authorisedConsent(..) gives the test an authorised consent for cust-1, which GET /accounts needs in the Consent-ID header.
  • TypeRef<List<Account>> maps a JSON array at the root to a list of records.
  • extracting(Account::type) turns the list of accounts into a list of types, so one assertion checks them all, in order.

Checkpoint: run the class again. Four tests pass.

Handle Fields the Record Doesn’t Match

See Unknown Fields Ignored

Goal: map accounts that carry fields the record doesn’t have.

1
2
3
4
5
6
7
8
9
10
11
@Test
void unknownFieldsAreIgnoredByDefault() {
    String consentId = authorisedConsent("cust-2", List.of("ReadAccountsBasic"));

    List<Account> accounts = consentsApi()
        .header("Consent-ID", consentId)
        .when().get("/accounts")
        .then().extract().as(new TypeRef<>() {});

    assertThat(accounts).isNotEmpty();
}

What’s happening:

  • Each account has productCode and balance, which the Account record leaves out on purpose.
  • Jackson 3 ignores unknown properties by default; Jackson 2 failed on them. So when the API adds a field, tests that don’t care about it keep passing.
  • new TypeRef<>() {} works too: Java infers the type argument from the variable.

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

Ignoring unknown fields has a cost: a record component without a matching field silently stays null. The JSON field _links isn’t a valid Java name, so Consent maps it with @JsonProperty("_links"). Without the annotation, links() is null, with no warning, and authorisedConsent(..) fails later with a NullPointerException.

When you do want to notice new or misnamed fields, section 4 makes the mapper strict.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-04 -Dtest=ObjectMappingTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_04.section_03.ObjectMappingTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.242 s -- in com.javanibble.module_04.section_03.ObjectMappingTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In aJsonArrayAsAList, change containsExactly("CURRENT", "SAVINGS") to containsExactly("SAVINGS", "CURRENT") and run the command again. You should see a result similar to the following:

1
2
3
4
5
6
7
8
9
[ERROR] Failures:
[ERROR]   ObjectMappingTest.aJsonArrayAsAList:110
Expecting actual:
  ["CURRENT", "SAVINGS"]
to contain exactly (and in same order):
  ["SAVINGS", "CURRENT"]
but there were differences at these indexes:
  - element at index 0: expected "SAVINGS" but was "CURRENT"
  - element at index 1: expected "CURRENT" but was "SAVINGS"

AssertJ shows the extracted list, the expected one, and every index where they differ. Because extracting(..) read the types from records, the message shows plain values, not JSON.

Change the order back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
ClassCastException: class java.util.LinkedHashMap cannot be cast to ...A generic type was mapped without a TypeRefUse as(new TypeRef<Page<Customer>>() {})
TypeRef is abstract; cannot be instantiatedThe {} is missing after new TypeRef<..>()Add {} to create the subclass
A record component is null though the JSON has the fieldThe component’s name doesn’t match the JSON fieldRename it, or add @JsonProperty("..")

Try It Yourself

Exercise 1: Map Another Customer

Add a test called emilyClarkeIsARetailCustomer that maps cust-4 to a Customer record and checks its name "Emily Clarke", email "emily@example.co.uk" and segment "RETAIL" in one AssertJ statement.

Hint

Combine aRecord with the returns(expected, getter) chain from aRecordInAndARecordOut.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void emilyClarkeIsARetailCustomer() {
    Customer customer = consentsApi()
    .when()
        .get("/customers/{id}", "cust-4")
    .then()
        .statusCode(200)
        .extract().as(Customer.class);

    assertThat(customer)
        .returns("Emily Clarke", Customer::name)
        .returns("emily@example.co.uk", Customer::email)
        .returns("RETAIL", Customer::segment);
}

Add a test called aNewConsentAwaitsAuthorisation. Create a consent for cust-3 with the permissions ReadAccountsBasic and ReadBalances, and map the response to a Consent record. Check that its status is "AWAITING_AUTHORISATION", that the permissions are exactly those two in order, that its links include self and authorise, and that the self link is /api/v1/consents/ followed by the consent id.

Hint

Start from the first chain in authorisedConsent(..). links() is a Map<String, Link>, so AssertJ’s containsKeys(..) applies to it.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void aNewConsentAwaitsAuthorisation() {
    Consent consent = consentsApi()
        .contentType(ContentType.JSON)
        .body(new NewConsent("cust-3", List.of("ReadAccountsBasic", "ReadBalances")))
    .when()
        .post("/consents")
    .then()
        .statusCode(201)
        .extract().as(Consent.class);

    assertThat(consent.status()).isEqualTo("AWAITING_AUTHORISATION");
    assertThat(consent.permissions()).containsExactly("ReadAccountsBasic", "ReadBalances");
    assertThat(consent.links()).containsKeys("self", "authorise");
    assertThat(consent.links().get("self").href()).isEqualTo("/api/v1/consents/" + consent.consentId());
}

Summary

You built ObjectMappingTest, which maps a customer, a created customer, a page of customers and a list of accounts to records, and shows how fields the records don’t have are handled. A misspelled field is now a compile error, not a null at runtime.

  • extract().as(Type.class) maps a response body to a record with the object mapper on the classpath, Jackson 3 here.
  • The same mapper writes request bodies, so a record can go in and another come back.
  • Generic types such as Page<Customer> and List<Account> need a TypeRef, an anonymous subclass that keeps the type argument; don’t forget the {}.
  • Jackson 3 ignores fields the record doesn’t have, so new API fields don’t break tests, but a misnamed component stays null; map invalid names with @JsonProperty.
  • Write the records from the API’s contract, and assert on them with AssertJ’s returns, extracting and allSatisfy.

Here are the commands you used in this guide:

1
mvn test -pl module-04 -Dtest=ObjectMappingTest

What’s Next

Next: continue with Configure the Object Mapper in REST Assured, which chooses the mapper explicitly and plugs in a strict Jackson 3 mapper.

The code:

Go deeper:

Related guides:

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