Post

Test an RFC 9457 Error Contract in REST Assured

Check every error response against one RFC 9457 problem schema, use draft 2020-12 if/then/else so a 422 must list field errors and other statuses must not, and test the schema itself.

Test an RFC 9457 Error Contract in REST Assured

Your payment API’s errors were written by different people at different times. One error has a message, another an error, and a third is an HTML page, so the mobile app can’t show the user what went wrong. Every error test checks statusCode(404) or statusCode(422), and they all pass. In this guide, you’ll describe the shape every error must have with one RFC 9457 schema, check every error against it in one call, and test the schema itself.

Level: Intermediate · Time: 20 minutes · Part of: Module 6: Schema and Contract Validation, section 2

What You’ll Build

You’ll build a test class called ErrorContractTest with five tests. Four trigger a different error, 404, 400, 415 and 422, and check each one against the same problem specification. The fifth tests the schema itself, with examples it must reject.

One of the tests sends an invalid payment and checks this error:

1
2
3
4
5
6
7
8
9
10
POST /pisp/v1/domestic-payments HTTP/1.1
Host: localhost:<port>
Content-Type: application/json

{"instructionId": "INV-1", "amount": {"value": "1", "currency": "euro"}}

HTTP/1.1 422
Content-type: application/problem+json; charset=utf-8

{"type":"about:blank","title":"Unprocessable Content","status":422,"errors":[{"field":"debtor", ...}, ...], ...}

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:

  • Build a specification for every error.
  • Check errors of different kinds.
  • Check that validation errors list the fields.
  • Test the schema itself.

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 ErrorContractTest 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 (ErrorContractTest.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 Validate Responses Against a JSON Schema in REST Assured.

Out of scope: this guide doesn’t cover checking every response against an OpenAPI description; that’s taught in section 4.

Understand Error Contracts

The problem. Error responses get less attention than successful ones. When each endpoint’s errors take their own shape, a client has to handle each one differently, and a test that checks only the status code can’t tell a proper error from an HTML stack trace.

The concept. RFC 9457 defines problem details, a standard JSON shape for HTTP errors, with the content type application/problem+json:

FieldMeaning
typeA URI that identifies the kind of problem; about:blank when there’s none
titleA short, human-readable summary
statusThe HTTP status code, repeated in the body
detailAn explanation of this occurrence
instanceThe path of the request that failed

APIs may add their own fields: the payment initiation API adds errors, a list of field errors, to validation failures. Its contract is:

  • Every error is application/problem+json with at least type, title and status.
  • A 422 must list the invalid fields in errors.
  • Any other status must not have errors.

When to use it. Check every error test against the contract, as well as its status code. Keep the status in the test, because errors have many, and the shape in a shared specification. Test the schema too, because a schema that’s too lenient makes every test that uses it pass for the wrong reason.

Give every error one shape, and check that shape on every error.

Meet the API Under Test

The tests use the payment initiation API from the previous section. It returns four kinds of error:

RequestStatusdetail
GET /domestic-payments/pmt-999404Payment pmt-999 does not exist
POST /domestic-payments with { not json400The body is not valid JSON
POST /domestic-payments with text/plain415Expected a JSON body, got Content-Type 'text/plain; charset=ISO-8859-1'
POST /domestic-payments with invalid fields422The request has invalid fields, plus errors

A 422 looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
    "type": "about:blank",
    "title": "Unprocessable Content",
    "status": 422,
    "detail": "The request has invalid fields",
    "instance": "/pisp/v1/domestic-payments",
    "errors": [
        { "field": "debtor", "detail": "is required and must be an object" },
        { "field": "creditor", "detail": "is required and must be an object" },
        { "field": "amount.value", "detail": "is required and must match [0-9]{1,13}\\.[0-9]{2}" },
        { "field": "amount.currency", "detail": "is required and must match [A-Z]{3}" }
    ]
}

The module’s problem schema describes the contract:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["type", "title", "status"],
  "properties": {
    "type": { "type": "string" },
    "title": { "type": "string" },
    "status": { "type": "integer", "minimum": 400, "maximum": 599 },
    "detail": { "type": "string" },
    "instance": { "type": "string" },
    "errors": {
      "type": "array",
      "minItems": 1,
      "items": {
        "type": "object",
        "required": ["field", "detail"],
        "properties": { "field": { "type": "string" }, "detail": { "type": "string" } }
      }
    }
  },
  "if": { "properties": { "status": { "const": 422 } } },
  "then": { "required": ["errors"] },
  "else": { "not": { "required": ["errors"] } }
}

The last three keywords make one rule depend on another:

  • if the status is 422,
  • then errors is required,
  • else errors must not be there.

minItems: 1 adds that a 422 can’t have an empty list of errors.

Build a Specification for Every Error

Set Up the Test Class

Goal: create the test class with a response specification that checks any error’s content type and shape.

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

import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;

import com.javanibble.pisp.PaymentInitiationApi;

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

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

class ErrorContractTest {

    private static PaymentInitiationApi api;
    private static ResponseSpecification problem;

    @BeforeAll
    static void startApi() {
        api = PaymentInitiationApi.start();
        problem = new ResponseSpecBuilder()
            .expectContentType("application/problem+json")
            .expectBody(matchesJsonSchemaInClasspath("schemas/problem.schema.json"))
            .build();
    }

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

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

What’s happening:

  • problem combines the content type and the schema in one response specification.
  • expectBody(matcher) without a path passes the whole body to the matcher, like body(matcher).
  • Now spec(problem) checks any error in one call.

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

Use the exact content type when the problem media type is part of the contract. ContentType.JSON accepts application/problem+json, but it also accepts plain application/json, so it can’t tell a problem from an ordinary JSON body.

Check Errors of Different Kinds

Check a 404, a 400 and a 415

Goal: trigger three different errors, and check each against the same contract.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void notFound() {
    pisp().when().get("/domestic-payments/{id}", "pmt-999").then().statusCode(404).spec(problem);
}

@Test
void malformedJson() {
    pisp().contentType(ContentType.JSON).body("{ not json").when().post("/domestic-payments")
        .then().statusCode(400).spec(problem);
}

@Test
void wrongContentType() {
    pisp().contentType(ContentType.TEXT).body("hello").when().post("/domestic-payments")
        .then().statusCode(415).spec(problem);
}

What’s happening:

  • Each test triggers a different code path in the API: an unknown id, a body that isn’t JSON, and the wrong content type.
  • Each states the status it expects, and spec(problem) checks the shape.
  • Three code paths, one contract.

Checkpoint: run ErrorContractTest from your IDE. Three tests run and pass.

Don’t check only the status of an error. A 404 with an HTML body passes statusCode(404). Add spec(problem) to every error test, and keep the status out of the specification, because errors have many statuses.

Check That Validation Errors List the Fields

Send an Invalid Payment

Goal: check a 422 against the contract, then check which fields it reports.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void validationErrorsListTheFields() {
    pisp()
        .contentType(ContentType.JSON)
        .body("{\"instructionId\": \"INV-1\", \"amount\": {\"value\": \"1\", \"currency\": \"euro\"}}")
    .when()
        .post("/domestic-payments")
    .then()
        .statusCode(422)
        .spec(problem)
        .body("errors.field", hasItems("debtor", "creditor", "amount.value", "amount.currency"));
}

What’s happening:

  • The body has no debtor or creditor, a one-digit amount and a lower-case currency.
  • spec(problem) checks the shape, and its if/then rule guarantees that errors is there.
  • So the test can go further, and check which fields are reported.

Checkpoint: run the class again. Four tests pass.

Test the Schema Itself

Reject the Cases the Condition Exists For

Goal: prove that the schema rejects a 422 without errors and a 404 with them.

A schema is code. If it’s too lenient, every test that uses it passes for the wrong reason, so the schema gets its own test:

1
2
3
4
5
6
7
8
@Test
void theSchemaItselfIsStrictAboutErrors() {
    assertThat("{\"type\":\"about:blank\",\"title\":\"Unprocessable Content\",\"status\":422}",
            not(matchesJsonSchemaInClasspath("schemas/problem.schema.json")));
    assertThat("{\"type\":\"about:blank\",\"title\":\"Not Found\",\"status\":404,"
                    + "\"errors\":[{\"field\":\"id\",\"detail\":\"unknown\"}]}",
            not(matchesJsonSchemaInClasspath("schemas/problem.schema.json")));
}

What’s happening:

  • A 422 without errors must be rejected. Without not(..), the report says $: required property 'errors' not found.
  • A 404 with errors must be rejected too. Without not(..), the report says $: must not be valid to the schema {"required":["errors"]}.
  • These two strings are the cases the if/then/else exists for. If someone simplifies the schema and drops the condition, this test fails.

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

Declare $schema for conditional rules. The older validator, used when a schema has no $schema, silently ignores if/then/else and const: the same schema without its $schema line accepts a 422 without errors. A test like this one catches that.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-06 -Dtest=ErrorContractTest

You should see a result similar to the following:

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

Make a Test Fail

In src/test/resources/schemas/problem.schema.json, change "minimum": 400 to "minimum": 500 and run the command again. You should see four failures similar to the following:

1
2
3
4
5
6
7
[ERROR] Failures:
[ERROR]   ErrorContractTest.notFound:52 1 expectation failed.
Response body doesn't match expectation.
Expected: The content to match the given JSON schema.
$.status: must have a minimum value of 500

  Actual: {"type":"about:blank","title":"Not Found","status":404, ...}

Every test of a 4xx error fails with the same line, because they all share the schema. That’s the point of one contract: one change to it reaches every error test at once. theSchemaItselfIsStrictAboutErrors still passes, because both its examples are rejected anyway.

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

Troubleshooting

SymptomLikely causeFix
$: required property 'errors' not foundA 422 doesn’t list its field errorsAdd errors to the API’s validation response
$: must not be valid to the schema {"required":["errors"]}A status other than 422 has errorsRemove errors from that response
Expected content-type "application/problem+json" doesn't match ...The error was sent as plain JSON, or as HTMLSend errors as application/problem+json
A schema accepts a 422 without errorsThe schema has no $schema, so the older validator ignores the conditionDeclare draft 2020-12 with $schema

Try It Yourself

Exercise 1: Report Exactly One Missing Field

Add a test called aMissingDebtorIsTheOnlyError that posts a payment with an instruction id, a creditor and a valid amount, but no debtor. Check that the API answers 422, that the error matches the contract, and that errors.field contains exactly debtor.

Hint

Start from validationErrorsListTheFields. Use contains(..) rather than hasItems(..), so an extra field error fails the test.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void aMissingDebtorIsTheOnlyError() {
    pisp()
        .contentType(ContentType.JSON)
        .body("""
            {"instructionId": "INV-2",
             "creditor": {"iban": "NL69INGB0123456789", "name": "Jan Jansen"},
             "amount": {"value": "10.00", "currency": "EUR"}}
            """)
    .when()
        .post("/domestic-payments")
    .then()
        .statusCode(422)
        .spec(problem)
        .body("errors.field", contains("debtor"));
}

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

Exercise 2: Test the Schema’s Other Rules

Add a test called theSchemaRejectsOtherBrokenProblems that checks the problem schema against four examples: a problem with status 200 must be rejected; a 422 with an empty errors list must be rejected; a 422 with one field error must be accepted; and a problem without type must be rejected.

Hint

Each rejection comes from a different keyword: minimum, minItems and required. Use assertThat(..) with not(..) for the rejections, as theSchemaItselfIsStrictAboutErrors does.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void theSchemaRejectsOtherBrokenProblems() {
    String schema = "schemas/problem.schema.json";

    assertThat("{\"type\":\"about:blank\",\"title\":\"OK\",\"status\":200}",
            not(matchesJsonSchemaInClasspath(schema)));
    assertThat("{\"type\":\"about:blank\",\"title\":\"Unprocessable Content\",\"status\":422,\"errors\":[]}",
            not(matchesJsonSchemaInClasspath(schema)));
    assertThat("{\"type\":\"about:blank\",\"title\":\"Unprocessable Content\",\"status\":422,"
                    + "\"errors\":[{\"field\":\"debtor\",\"detail\":\"is required\"}]}",
            matchesJsonSchemaInClasspath(schema));
    assertThat("{\"title\":\"Not Found\",\"status\":404}",
            not(matchesJsonSchemaInClasspath(schema)));
}

Summary

You built ErrorContractTest, which checks four kinds of error against one RFC 9457 problem specification, checks which fields a 422 reports, and tests the schema with examples it must reject. An error in the wrong shape, or an HTML page, now fails its test whatever its status.

  • An error contract gives every error the same shape, so clients can handle them all one way; RFC 9457 problem details are a ready-made shape.
  • One JSON Schema describes the contract, and a response specification combines it with the content type, so spec(problem) checks any error in one call.
  • Draft 2020-12’s if/then/else expresses rules that depend on the status, such as “a 422 must list its field errors, and nothing else may”.
  • Keep the status in each test and the shape in the specification.
  • Test the schema itself with examples it must reject, and declare $schema, or conditional rules are silently ignored.

Here are the commands you used in this guide:

1
mvn test -pl module-06 -Dtest=ErrorContractTest

What’s Next

Next: continue with Validate ISO 20022 XML Against an XSD in REST Assured, which validates an ISO 20022 payment file and its status report against XSDs.

The code:

Go deeper:

Related guides:

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