Post

Use Parsers and Failure Listeners in REST Assured

Read a JSON body sent as text/plain with parser(..) per response or registerParser(..) in a response specification, learn why a spec's parser doesn't reach checks chained after it, and collect evidence with a ResponseValidationFailureListener.

Use Parsers and Failure Listeners in REST Assured

The legacy exchange-rate service sends perfectly good JSON, labelled text/plain. REST Assured decides how to read a body from its content type, so every body path fails with an error about unsupported content types. You can’t change the service, and repairing the response in a filter hides its real content type. And when a check against it does fail at night, the CI log says only Expected status code <200> but was <500>, with nothing to attach to a ticket. In this guide, you’ll tell REST Assured how to read the body, and capture the response of every failed check.

Level: Advanced · Time: 20 minutes · Part of: Module 8: Filters and Extensibility, section 5

What You’ll Build

You’ll build a test class called ParsersAndListenersTest with four tests. One shows the body as plain text. Two read it as JSON, once for one response and once in a response specification. The last collects evidence from a failed check with a failure listener.

With a parser, body paths work, and the response keeps its real content type:

1
2
3
4
.then()
    .parser("text/plain", Parser.JSON)
    .body("base", equalTo("EUR"))
    .body("rates.USD", equalTo(1.09f));

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:

  • Read a mislabelled body.
  • Collect evidence on failure.

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 ParsersAndListenersTest 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 (ParsersAndListenersTest.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 Write Request and Response Filters in REST Assured.

Out of scope: this guide doesn’t cover writing a parser of your own, or wiring a listener into a reporting tool such as Allure; the listener here collects evidence in a list.

Understand Parsers and Failure Listeners

The problem. Body paths depend on the content type: REST Assured reads application/json as JSON and application/xml as XML, and refuses anything it doesn’t know. A service that labels JSON as text/plain breaks every path, though its body is fine. Separately, a failed check reports what was expected, but not the response that failed it, which is the evidence a bug report needs.

The concept. A parser tells REST Assured how to read a content type for body paths: Parser.JSON, Parser.XML, Parser.HTML or Parser.TEXT. You can map a content type to a parser in three places:

WhereHowApplies to
One responsethen().parser(contentType, parser)The checks after it in that chain
A response specificationResponseSpecBuilder.registerParser(..)That specification’s own expectations
GloballyRestAssured.registerParser(..)Every response, until RestAssured.reset()

A failure listener, ResponseValidationFailureListener, is a functional interface that REST Assured calls when validation fails, with the request specification, the response specification and the response. You set it with FailureConfig.

When to use each. Use parser(..) for one response, and registerParser(..) when the checks for an endpoint live in a specification. Prefer either to a filter that rewrites the content type, because a parser leaves the response as it was. Add a failure listener wherever a failure needs more evidence than its message.

Tell REST Assured how to read a response; don’t change what the response says.

Meet the API Under Test

SignedPaymentsApi has one endpoint that behaves like an old system. GET /api/v1/legacy/fx-rates needs no authentication, and returns exchange rates. The body is JSON, but the content type is text/plain:

1
2
3
4
HTTP/1.1 200 OK
Content-Type: text/plain

{"base":"EUR","rates":{"GBP":0.85,"USD":1.09,"SEK":11.42}}

Your tests check these values:

  • The content type, which stays text/plain in every test.
  • base, the base currency, EUR.
  • rates.GBP, rates.USD and rates.SEK, which JSON paths read as floats.
  • The evidence the listener collects: the status and the body.

Read a Mislabelled Body

Set Up the Test Class

Goal: create the test class with the API and a helper for requests to it.

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_08.section_05;

import static io.restassured.RestAssured.given;
import static io.restassured.config.FailureConfig.failureConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.javanibble.signing.SignedPaymentsApi;

import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.listener.ResponseValidationFailureListener;
import io.restassured.parsing.Parser;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;

import java.util.ArrayList;
import java.util.List;

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

class ParsersAndListenersTest {

    private static SignedPaymentsApi api;

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

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

    private static RequestSpecification legacy() {
        return given().baseUri(api.baseUri()).port(api.port());
    }
}

What’s happening:

  • legacy() points a request at the API. The legacy endpoint needs no key, correlation id or signature, so the tests need no filters.

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

See the Body as Text

Goal: show what works on a text/plain body without help.

Add this test to the class:

1
2
3
4
5
6
7
8
9
@Test
void withoutHelpTheBodyIsJustText() {
    legacy()
    .when()
        .get("/api/v1/legacy/fx-rates")
    .then()
        .contentType("text/plain")
        .body(equalTo("{\"base\":\"EUR\",\"rates\":{\"GBP\":0.85,\"USD\":1.09,\"SEK\":11.42}}"));
}

What’s happening:

  • A matcher on the whole body works, because it compares text.
  • A body path doesn’t. body("base", equalTo("EUR")) throws IllegalStateException: Expected response body to be verified as JSON, HTML or XML but content-type 'text/plain' is not supported out of the box, and suggests RestAssured.registerParser(..).
  • The suggestion is a global parser. There are better places for it.

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

Parse Text as JSON for One Response

Goal: read the body with JSON paths, without changing the response.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void parseTextAsJsonForOneResponse() {
    legacy()
    .when()
        .get("/api/v1/legacy/fx-rates")
    .then()
        .parser("text/plain", Parser.JSON)
        .body("base", equalTo("EUR"))
        .body("rates.USD", equalTo(1.09f));
}

What’s happening:

  • parser("text/plain", Parser.JSON) tells REST Assured to read text/plain as JSON for the checks that follow it.
  • JSON paths read numbers as floats, so the rate is 1.09f.
  • The response is unchanged: a contentType("text/plain") check after the parser still passes, so it still tells the truth. That’s the advantage over repairing the response with a filter.

Checkpoint: run the class again. Two tests pass.

Put parser(..) before the body checks. With body("base", ..) before parser(..) in the chain, the test failed with the same IllegalStateException as without a parser.

Parse It in a Response Specification

Goal: keep the parser and the checks for the legacy endpoint together.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void orInAResponseSpecification() {
    // A parser registered in a specification applies to the specification's own expectations. Merging it with
    // spec(..) doesn't carry the parser over, so a body path chained after spec(..) would still see text/plain.
    // Put the body expectations in the specification, or use parser(..) on the response.
    ResponseSpecification legacyJson = new ResponseSpecBuilder()
        .registerParser("text/plain", Parser.JSON)
        .expectStatusCode(200)
        .expectBody("rates.SEK", equalTo(11.42f))
        .build();

    legacy()
    .when()
        .get("/api/v1/legacy/fx-rates")
    .then()
        .spec(legacyJson);
}

What’s happening:

  • registerParser(..) adds the parser to the specification, next to the expectations that need it.
  • then().spec(legacyJson) runs the specification’s checks, including the rates.SEK path, with its parser.

Checkpoint: run the class again. Three tests pass.

A specification’s parser doesn’t reach the chain. then().spec(legacyJson).body("base", equalTo("EUR")) fails with the same IllegalStateException, and so does then().body("base", ..).spec(legacyJson). Keep the body checks in the specification, or add parser(..) to the chain.

Collect Evidence on Failure

Add a Failure Listener

Goal: capture the response of a failed check, so the failure comes with evidence.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void aFailureListenerSeesTheResponseOfAFailedTest() {
    // Attach evidence to a failure: report the response to a test report, a ticket or a screenshot-like file.
    List<String> evidence = new ArrayList<>();
    ResponseValidationFailureListener collectEvidence =
            (requestSpec, responseSpec, response) -> evidence.add(response.statusCode() + " " + response.asString());

    assertThrows(AssertionError.class, () ->
        legacy()
            .config(config().failureConfig(failureConfig().failureListeners(collectEvidence)))
        .when()
            .get("/api/v1/legacy/fx-rates")
        .then()
            .statusCode(500));                                   // fails: the status is 200

    assertEquals(1, evidence.size());
    assertEquals("200 {\"base\":\"EUR\",\"rates\":{\"GBP\":0.85,\"USD\":1.09,\"SEK\":11.42}}", evidence.getFirst());
}

What’s happening:

  • The listener is a lambda that adds the status and the body to a list. failureConfig().failureListeners(..) puts it in the request’s configuration.
  • The check expects 500 and gets 200, so validation fails. REST Assured calls the listener once, then throws the AssertionError, which assertThrows(..) catches.
  • The list holds the evidence: the status and the whole body.

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

A listener is called only on failure, so a passing suite does no extra work: a passing request left the list empty. It’s called once per failed validation, however many expectations fail: with both statusCode(500) and a wrong contentType(..) failing, it ran once. It’s called for a parser error too: a body path on the unparsed text/plain body called it before the IllegalStateException.

Unlike log().ifValidationFails(), which prints to a stream, a listener can do anything with the evidence: attach it to a test report, write it to a file, or add it to a ticket.

Keep listeners simple and defensive. A listener that threw IllegalStateException("listener broke") replaced the test’s AssertionError: the report showed the listener’s exception, and the real failure was gone.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-08 -Dtest=ParsersAndListenersTest

You should see a result similar to the following:

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

Make a Test Fail

In parseTextAsJsonForOneResponse, delete the .parser("text/plain", Parser.JSON) line and run the command again. You should see a result similar to the following:

1
2
3
4
5
6
[ERROR] Errors:
[ERROR]   ParsersAndListenersTest.parseTextAsJsonForOneResponse:66 » IllegalState Expected response body to be verified as JSON, HTML or XML but content-type 'text/plain' is not supported out of the box.
Try registering a custom parser using:
   RestAssured.registerParser("text/plain", <parser type>);
Content was:
{"base":"EUR","rates":{"GBP":0.85,"USD":1.09,"SEK":11.42}}

Without the parser, REST Assured doesn’t know how to read text/plain for a path. JUnit reports an error, not a failure, because REST Assured threw before it could compare a value. The message shows the body, which tells you the content is JSON, and the content type is the problem.

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

Troubleshooting

SymptomLikely causeFix
content-type 'text/plain' is not supported out of the boxNo parser for the content typeAdd parser(..) before the body checks, or registerParser(..) in the specification
The same error with a parser in the specificationThe path is chained after spec(..), outside the specificationMove the check into the specification, or add parser(..) to the chain
Cannot determine which path implementation to use on extract().path(..)extract() has no parser for the content type eitherAdd parser(..) before extract()
A failed test reports the listener’s exceptionThe listener threwCatch exceptions inside the listener
groovy.json.JsonException: Lexing failed on a real text bodyA global JSON parser for text/plainUse parser(..) per response, and RestAssured.reset() after global parsers

Try It Yourself

Exercise 1: Extract a Rate

Add a test called extractARate. Use parser(..) and extract().path(..) to read rates.GBP from the legacy response, and check that it equals 0.85f.

Hint

extract() needs the parser too: without it, extract().path(..) throws Cannot determine which path implementation to use because the content-type text/plain doesn't map to a path implementation. Put parser(..) between then() and extract().

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void extractARate() {
    float gbp = legacy()
        .when()
            .get("/api/v1/legacy/fx-rates")
        .then()
            .parser("text/plain", Parser.JSON)
            .extract().path("rates.GBP");

    assertEquals(0.85f, gbp);
}

response.jsonPath() reads the body as JSON whatever the content type, so legacy().get(..).jsonPath().getFloat("rates.GBP") works too, without a parser.

Exercise 2: Share a Listener in a Specification

Add a test called aListenerInASpecification. Build a request specification with the base URI, the port and a configuration with a listener that adds the status to a list. Send one request that passes and one that fails with statusCode(500), and check that the list holds only "200".

Hint

RequestSpecBuilder.setConfig(config().failureConfig(..)) puts the listener in the specification. Wrap the failing request in assertThrows(AssertionError.class, ..). You need an import for RequestSpecBuilder.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void aListenerInASpecification() {
    List<String> evidence = new ArrayList<>();
    ResponseValidationFailureListener collectStatus =
            (requestSpec, responseSpec, response) -> evidence.add(String.valueOf(response.statusCode()));
    RequestSpecification spec = new RequestSpecBuilder()
        .setBaseUri(api.baseUri()).setPort(api.port())
        .setConfig(config().failureConfig(failureConfig().failureListeners(collectStatus)))
        .build();

    given(spec).when().get("/api/v1/legacy/fx-rates").then().statusCode(200);
    assertThrows(AssertionError.class, () ->
        given(spec).when().get("/api/v1/legacy/fx-rates").then().statusCode(500));

    assertEquals(List.of("200"), evidence);
}

Add import io.restassured.builder.RequestSpecBuilder; to the class.

Summary

You built ParsersAndListenersTest, which reads the legacy endpoint’s mislabelled JSON with a parser, once per response and once in a response specification, and collects the response of a failed check with a failure listener. The legacy endpoint keeps its real content type in every test, and a failure brings its evidence along.

  • REST Assured picks a parser from the content type, so JSON sent as text/plain can’t be read with a path.
  • then().parser(contentType, Parser.JSON) fixes that for the checks after it, without changing the response.
  • registerParser(..) in a response specification works for that specification’s own expectations only; it doesn’t reach checks chained after spec(..).
  • A global parser affects every response of that type, including real text, so use it only with reset().
  • A ResponseValidationFailureListener, set with FailureConfig, is called once per failed validation and sees the response; keep it from throwing.

Here are the commands you used in this guide:

1
mvn test -pl module-08 -Dtest=ParsersAndListenersTest

What’s Next

Next: you’ve finished Module 8. Continue with Module 9: Data-Driven Tests and API Workflows, starting with Write Parameterized API Tests With REST Assured, which tests many inputs without copying tests.

The code:

Go deeper:

Related guides:

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