Post

Share Response Checks With Response Specifications in REST Assured

Put the expectations many responses share into a ResponseSpecification, use it with then().spec(..) or given(request, response), check a shared error shape, and see every failure of a specification reported at once.

Share Response Checks With Response Specifications in REST Assured

Every successful response of the Open Banking API should be 200, be JSON, echo the interaction id and carry a Links.Self. Every error should be an RFC 9457 problem. Your tests write those checks again and again, and one of them forgets the interaction id, so a release that stops echoing it goes unnoticed. In this guide, you’ll put the checks that many responses share into response specifications, so every test checks them all.

Level: Intermediate · Time: 20 minutes · Part of: Module 5: Reusable Specifications and Configuration, section 2

What You’ll Build

You’ll build a test class called ResponseSpecificationTest with four tests. It builds one response specification for every success and one for the shape of every error, applies them in two ways, and checks the message a specification gives when several of its expectations fail.

Two of the tests check the shape of this error:

1
2
3
4
5
6
7
8
9
10
GET /open-banking/v4.0/aisp/accounts/99999 HTTP/1.1
Host: localhost:<port>
Authorization: Bearer test-token
x-fapi-interaction-id: b8aee206-69fb-4116-8721-65555b109831

HTTP/1.1 404 Not Found
Content-type: application/problem+json; charset=utf-8
X-fapi-interaction-id: b8aee206-69fb-4116-8721-65555b109831

{"type":"about:blank","title":"Not Found","status":404,"detail":"Account 99999 does not exist", ...}

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:

  • Build shared response specifications.
  • Apply a specification after the request.
  • Apply both specifications in given(..).
  • Read every failure of a specification.

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 ResponseSpecificationTest 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 (ResponseSpecificationTest.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 Build Reusable Request Specifications in REST Assured.

Out of scope: this guide doesn’t cover validating a whole body against a JSON Schema or an OpenAPI contract; that’s taught in Module 6.

Understand Response Specifications

The problem. Request specifications remove the repetition at the start of a test. The end of a test repeats too: the status, the content type, the headers and fields that every response of a kind must have. Repeated checks drift, and a test that forgets one lets a regression through.

The concept. A ResponseSpecification is a set of expectations for a response, built with ResponseSpecBuilder:

MethodExpects
expectStatusCode(..)A status code
expectContentType(..)A content type
expectHeader(name, ..)A header value, or a matcher for it
expectBody(path, matcher)A value in the body
addResponseSpecification(other)Everything another specification expects

build() returns the finished, immutable specification. You apply it with then().spec(spec) after the request, or with given(request, response) before it. A specification is checked as a whole, so every expectation that fails is reported, unlike a chain of separate then() calls.

When to use it. Keep one specification for what every success has in common, and one for the shape of every error. Leave what’s special about a response, such as a list’s size or an error’s status code, to the test, so a reader sees at once what the test is about.

Share what every response must have, and keep what’s special in the test.

Meet the API Under Test

The tests use the Open Banking API from the previous section. Every successful response:

  • Has status 200 and a JSON content type.
  • Echoes the request’s x-fapi-interaction-id header.
  • Has a Links.Self in the body, as in this balance of account 31820:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
    "Data": {
        "Balance": [
            {
                "AccountId": "31820",
                "Type": "InterimAvailable",
                "CreditDebitIndicator": "Credit",
                "Amount": { "Amount": "15000.00", "Currency": "EUR" }
            }
        ]
    },
    "Links": { "Self": "/open-banking/v4.0/aisp/accounts/31820/balances" },
    "Meta": { "TotalPages": 1 }
}

Every error is an RFC 9457 problem with the content type application/problem+json, such as the 404 for account 99999 shown above. The API echoes the interaction id on errors too, when the request sent one.

Your tests check these values:

  • The status, content type, interaction id, Content-Length and Links.Self of every success.
  • The content type, title and status of every problem.
  • Data.Account and Data.Balance[0].Amount.Amount, for what’s special about one response.

Build Shared Response Specifications

Set Up the Test Class

Goal: create the test class with a request specification, a success specification and a problem specification.

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
56
57
58
59
60
61
62
63
64
package com.javanibble.module_05.section_02;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.javanibble.openbanking.OpenBankingApi;

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;

import java.util.UUID;

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

class ResponseSpecificationTest {

    private static OpenBankingApi api;
    private static RequestSpecification openBanking;
    private static ResponseSpecification success;
    private static ResponseSpecification problem;

    @BeforeAll
    static void startApiAndBuildSpecifications() {
        api = OpenBankingApi.start();

        openBanking = new RequestSpecBuilder()
                .setBaseUri(api.baseUri()).setPort(api.port()).setBasePath(OpenBankingApi.BASE_PATH)
                .addHeader("Authorization", "Bearer test-token")
                .build();

        success = new ResponseSpecBuilder()
                .expectStatusCode(200)
                .expectContentType(ContentType.JSON)
                .expectHeader("x-fapi-interaction-id", matchesPattern("[0-9a-f-]{36}"))
                .expectHeader("Content-Length", response -> equalTo(String.valueOf(response.asByteArray().length)))
                .expectBody("Links.Self", notNullValue())
                .build();

        problem = new ResponseSpecBuilder()
                .expectContentType("application/problem+json")
                .expectBody("title", notNullValue())
                .expectBody("status", notNullValue())
                .build();
    }

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

    private static RequestSpecification request() {
        return given(openBanking).header("x-fapi-interaction-id", UUID.randomUUID().toString());
    }
}

What’s happening:

  • success describes every successful response: status, content type, an echoed interaction id, a correct Content-Length and a Links.Self.
  • The Content-Length check is a response-aware header expectation: the lambda receives the response, so the header is compared with the real length of the body.
  • problem describes the shape of every error, whatever its status.
  • request() adds a new interaction id to each request, because it must be new every time.

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

Response-aware expectations in expectHeader(..) are available since REST Assured 6.1. They work like the response-aware matchers you used after then().

Apply a Specification After the Request

Use then().spec(..)

Goal: check the shared expectations of a success, plus what’s special about this one.

1
2
3
4
5
6
7
8
9
@Test
void thenSpec() {
    request()
    .when()
        .get("/accounts")
    .then()
        .spec(success)
        .body("Data.Account", hasSize(3));
}

What’s happening:

  • spec(success) checks all five shared expectations.
  • body("Data.Account", hasSize(3)) adds the one check that’s special about this endpoint.

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

Keep test-specific checks out of a shared specification. A Data.Account size of 3 is true for one endpoint only; in success, it would fail every other test that uses it.

Check That an Error Has the Right Shape

Goal: check a 404’s status in the test, and its shape with the problem specification.

1
2
3
4
5
6
7
8
9
@Test
void errorsShareAShape() {
    request()
    .when()
        .get("/accounts/{id}", "99999")
    .then()
        .statusCode(404)
        .spec(problem);
}

What’s happening:

  • The status is specific to this test, so it stays in the test.
  • The shape of the body is shared by every error, so it lives in problem. Any error test in the suite can now prove the API answers with a proper problem.

Checkpoint: run the class again. Two tests pass.

Don’t put a status code in an error specification. 404, 400 and 401 are all problems, so problem would fit only one of them. Leave the status to the test, and the shape to the specification.

Apply Both Specifications in given(..)

Pass a Request and a Response Specification

Goal: read a balance with a complete request and the success specification, in one call.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void bothSpecificationsInGiven() {
    RequestSpecification withInteractionId = new RequestSpecBuilder()
        .addRequestSpecification(openBanking)
        .addHeader("x-fapi-interaction-id", UUID.randomUUID().toString())
        .build();

    given(withInteractionId, success)
        .get("/accounts/{id}/balances", "31820")
    .then()
        .body("Data.Balance[0].Amount.Amount", equalTo("15000.00"));
}

What’s happening:

  • given(request, response) returns a RequestSender, not a RequestSpecification, so the request must already be complete. The interaction id is built into a new request specification first.
  • A RequestSender has no when(), so get(..) is called directly.
  • success is checked when the response arrives, and then() adds the balance check.

Checkpoint: run the class again. Three tests pass.

You can’t add to the request after given(request, response). given(request, response).header("x", "y") doesn’t compile, with cannot find symbol, because a RequestSender has no header(..). Build everything into the request specification first.

Read Every Failure of a Specification

Capture a Specification’s Failure Message

Goal: apply the success specification to an error, and check that the message lists every expectation the response broke.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aSpecificationReportsAllItsFailuresAtOnce() {
    AssertionError error = assertThrows(AssertionError.class, () ->
        request()
        .when()
            .get("/accounts/{id}", "99999")
        .then()
            .spec(success));

    String message = error.getMessage();
    assertTrue(message.startsWith("2 expectations failed."), message);
    assertTrue(message.contains("Expected status code <200> but was <404>"), message);
    assertTrue(message.contains("Links.Self"), message);
}

What’s happening:

  • The 404 problem isn’t a success, so spec(success) fails, and assertThrows(..) captures the AssertionError.
  • Only two of the five expectations fail: the status and Links.Self. A problem is still JSON, because ContentType.JSON accepts any +json type, and the API echoes the interaction id on errors too.
  • The message lists both, so you see exactly which parts of the contract this response broke:
1
2
3
4
5
6
2 expectations failed.
Expected status code <200> but was <404>.

JSON path Links.Self doesn't match.
Expected: not null
  Actual: null

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

Don’t put a separate check before the specification. With statusCode(200) before spec(success), the chain stops at the status code and reports 1 expectation failed., hiding the other failures the specification would have listed.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-05 -Dtest=ResponseSpecificationTest

You should see a result similar to the following:

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

Make a Test Fail

In thenSpec, replace request() with given(openBanking), so the request has no interaction id, and run the command again. You should see a result similar to the following:

1
2
3
4
5
6
7
8
9
10
11
[ERROR] Failures:
[ERROR]   ResponseSpecificationTest.thenSpec:79 3 expectations failed.
Expected status code <200> but was <400>.

Expected header "x-fapi-interaction-id" was not a string matching the pattern '[0-9a-f-]{36}', was "null". Headers are:
Content-type=application/problem+json; charset=utf-8
...

JSON path Links.Self doesn't match.
Expected: not null
  Actual: null

The API rejected the request with 400, and because there was no interaction id to echo, the header expectation fails too. One run reports all three broken expectations, which is the point of checking a specification as a whole: you see the missing header, not only the status.

Change given(openBanking) back to request() and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
cannot find symbol on header(..) or when() after given(request, response)given(request, response) returns a RequestSenderBuild the header into the request specification, and call get(..) directly
A shared specification fails for one endpoint onlyIt holds a check that’s specific to another endpointMove that check into the test
Expected header "x-fapi-interaction-id" ... was "null"The request didn’t send an interaction idUse the request() helper
A failure reports 1 expectation failed. though more is wrongA separate check before spec(..) stopped the chainPut the specification first

Try It Yourself

Exercise 1: Reuse the Problem Shape

Add a test called everyErrorIsAProblem that checks two errors with the problem specification: the balances of the unknown account 99999 give 404 with a detail that names the account; and a request without the token gives 401.

Hint

Keep each status in the test, as errorsShareAShape does. For the request without the token, build it from given() with the base URI, port and base path, because openBanking carries the token.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void everyErrorIsAProblem() {
    request()
    .when()
        .get("/accounts/{id}/balances", "99999")
    .then()
        .statusCode(404)
        .spec(problem)
        .body("detail", containsString("99999"));

    given().baseUri(api.baseUri()).port(api.port()).basePath(OpenBankingApi.BASE_PATH)
        .header("x-fapi-interaction-id", UUID.randomUUID().toString())
    .when()
        .get("/accounts")
    .then()
        .statusCode(401)
        .spec(problem);
}

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

Exercise 2: Layer a Balance Specification

Add a test called everyAccountHasEuroBalances. Build a balances response specification on top of success with addResponseSpecification(..), expecting Data.Balance not to be empty and every balance’s Amount.Currency to be "EUR". Then, for each of the accounts 22289, 31820 and 40114, read the balances with given(request, balances), and check that the first balance belongs to that account.

Hint

Build a new request specification with an interaction id inside the loop, so every request gets a new one. Use not(empty()) and everyItem(equalTo("EUR")) from Hamcrest.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
void everyAccountHasEuroBalances() {
    ResponseSpecification balances = new ResponseSpecBuilder()
        .addResponseSpecification(success)
        .expectBody("Data.Balance", not(empty()))
        .expectBody("Data.Balance.Amount.Currency", everyItem(equalTo("EUR")))
        .build();

    for (String id : List.of("22289", "31820", "40114")) {
        RequestSpecification withInteractionId = new RequestSpecBuilder()
            .addRequestSpecification(openBanking)
            .addHeader("x-fapi-interaction-id", UUID.randomUUID().toString())
            .build();

        given(withInteractionId, balances)
            .get("/accounts/{id}/balances", id)
        .then()
            .body("Data.Balance[0].AccountId", equalTo(id));
    }
}

Add import java.util.List; and static imports for empty, everyItem and not from org.hamcrest.Matchers to the class.

Summary

You built ResponseSpecificationTest, which checks every success and every error with a shared specification, applies them with then().spec(..) and given(request, response), and reads the message a specification gives when several expectations fail. No test can forget the interaction id any more.

  • A ResponseSpecification, built with ResponseSpecBuilder, holds the expectations many responses share: status, content type, headers and body values.
  • Response-aware header expectations, since REST Assured 6.1, compare a header with the response itself, such as Content-Length with the body’s length.
  • Apply a specification with then().spec(..), or with given(request, response) when the request is complete; a RequestSender has no when() or header(..).
  • Keep one specification for success and one for the shape of errors, and leave what’s special, such as an error’s status, to the test.
  • A specification is checked as a whole, so its failure message lists every expectation the response broke; don’t put separate checks before it.

Here are the commands you used in this guide:

1
mvn test -pl module-05 -Dtest=ResponseSpecificationTest

What’s Next

Next: continue with Configure Timeouts, Redirects and Charsets in REST Assured, which configures timeouts, redirects and charsets for the client itself.

The code:

Go deeper:

Related guides:

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