Post

Take Apart a REST Assured Test

Write the same REST Assured test in its full, short and stored forms, learn the three types behind given/when/then, and fill your first path parameter.

Take Apart a REST Assured Test

You open a teammate’s test class for the Accounts API and find three tests that look nothing alike. One is a full given/when/then chain, one is get(url).then().statusCode(200) on a single line, and one keeps the response in a variable and checks it with JUnit’s assertEquals. In this guide, you’ll write all of those forms yourself and learn the three types that make them the same test.

Level: Beginner · Time: 20 minutes · Part of: Module 1: Foundations, section 2

What You’ll Build

You’ll build a test class called GivenWhenThenTest that writes the same health check in five forms, then adds a sixth test that requests an account with a path parameter.

The tests send these two requests and check these responses:

1
2
3
4
5
6
GET /api/health HTTP/1.1

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

{"status":"UP"}
1
2
3
4
5
6
GET /api/v1/accounts/acc-1001 HTTP/1.1

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

{"id":"acc-1001","owner":"Anna de Vries", ...}

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

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

In this guide, you will:

  • Write the full form of a test.
  • Shorten the chain for requests with no set-up.
  • Store the request and the response in variables.
  • Fill a path parameter.

What You Need

  • About 20 minutes
  • JDK 26 or later
  • Maven 3.9 or later
  • An IDE (IntelliJ IDEA, VS Code or Eclipse)
  • Knowledge: you can write a test that starts the Accounts API and checks a response with given/when/then, as taught in Send Your First REST Assured Request.

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create GivenWhenThenTest next to the FirstRequestTest class from the previous section, and follow every heading below.
  • Skip ahead: open the finished class (GivenWhenThenTest.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 Send Your First REST Assured Request.

Out of scope: this guide doesn’t explain how REST Assured builds the URL from baseUri, port and the path; that’s taught in Control Where REST Assured Requests Go. Named path parameters, query parameters and form parameters are taught in Module 2.

Understand the Types Behind given/when/then

The problem. The given/when/then chain reads like a sentence, so it’s tempting to treat it as fixed syntax. Then a test written on one line, or one that stores the response and uses assertEquals, looks like a different library. Your teammate’s three tests are all correct REST Assured, and they make sense once you know what the chain is made of.

The concept. A REST Assured chain is plain Java that passes through three types:

  • RequestSpecification, returned by given(), is a builder for the request: base URI, port, base path, headers, parameters and body.
  • Response, returned by get(..), post(..) and the other HTTP methods, is the response as an ordinary Java object, with a status code, headers and a body.
  • ValidatableResponse, returned by then(), checks the response with each call, such as statusCode(..), header(..) or body(..). A failed check throws an AssertionError at once.

Every shorter form either skips a step you don’t need or keeps one of these objects in a variable.

When to use each form. Use the full form in shared code, because it shows readers where the request, the action and the checks start. Use the one-line form only for trivial requests with no set-up. Store a RequestSpecification or a Response only when you need it later, for example to reuse a request or to read an id for the next call.

Write the full chain in shared code, and shorten it only when nothing is lost.

Meet the API Under Test

This guide uses two endpoints of the Accounts API:

MethodPathPurpose
GET/api/healthReport whether the service is up
GET/api/v1/accounts/{id}Fetch one account

The health endpoint answers GET /api/health with a response similar to the following:

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

{"status":"UP"}

The account endpoint answers GET /api/v1/accounts/{id} with one account. For acc-1001, you get a response similar to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-request-id: 8fa86e10-1467-433e-bb1a-98aa9d43bbaf
Content-length: 163
Cache-control: no-store

{
    "id": "acc-1001",
    "iban": "NL91ABNA0417164300",
    "owner": "Anna de Vries",
    "type": "CURRENT",
    "currency": "EUR",
    "balance": 1250.50,
    "status": "ACTIVE",
    "openedOn": "2019-04-01"
}

Your tests check two fields:

  • The health body’s status field, "UP", which every health check form reads.
  • The account’s owner field, "Anna de Vries", which the path parameter test reads.

Write the Full Form

The full form uses every part of the chain: given(), when() and then().

Set Up the Test Class

Goal: create the test class, start the API and build an absolute URL for the shorter forms.

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

import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;

import com.javanibble.accounts.AccountsApi;

import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

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

class GivenWhenThenTest {

    private static AccountsApi api;
    private static String healthUrl;

    @BeforeAll
    static void startApi() {
        api = AccountsApi.start();
        healthUrl = api.baseUri() + ":" + api.port() + "/api/health";
    }

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

What’s happening:

  • startApi() and stopApi() start and stop the Accounts API as in the previous section.
  • healthUrl is new: an absolute URL such as http://localhost:54321/api/health, built once the port is known. The shorter forms later in this guide send their requests to it.
  • The static imports for get, when and assertEquals, and the Response and RequestSpecification imports, are for later steps. Your IDE may mark them as unused until then.

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

Add the Syntactic Sugar

Goal: write the health check in its full form, including the methods that exist only for readability.

Some methods exist only to make the chain read like a sentence. This is called syntactic sugar: code that changes how a test reads, not what it does.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void fullForm() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/health")
    .then()
        .statusCode(200)
    .and()
        .body("status", equalTo("UP"));
}

What’s happening:

  • given() returns a RequestSpecification, and baseUri(..) and port(..) configure it.
  • when() returns the same RequestSpecification it was called on, so removing it changes nothing. Keeping it marks where Arrange ends and Act begins.
  • get(..) sends the request and returns a Response, and then() turns it into a ValidatableResponse.
  • and() is syntactic sugar too. It returns the same ValidatableResponse, so the body(..) check runs as if and() weren’t there.

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

Shorten the Chain

When a request needs no set-up, you can leave parts of the chain out.

Leave Out given()

Goal: send the same request without a given() block.

Compared with fullForm, the given() block is gone, and the chain starts with the static when():

1
2
3
4
5
6
7
@Test
void givenCanBeLeftOutWhenTheRequestNeedsNoSetUp() {
    when()
        .get(healthUrl)
    .then()
        .statusCode(200);
}

What’s happening:

  • The static when() on RestAssured starts a request with no set-up.
  • get(healthUrl) takes an absolute URL, so REST Assured needs no base URI or port.

Checkpoint: run the class again. Two tests pass.

With no given() block, a relative path such as "/api/health" goes to port 8080 on localhost, and the test fails with a ConnectException. Leave out given() only when the URL is absolute.

Write It on One Line

Goal: send the request and check the status code in a single line.

This time when() is gone too:

1
2
3
4
@Test
void theShortestForm() {
    get(healthUrl).then().statusCode(200);
}

What’s happening:

  • The static get(..) on RestAssured sends the request straight away and returns the Response.
  • then().statusCode(200) checks it as before.

This form is common in quick checks and older code bases. As soon as the request has headers or parameters, the full form reads better.

Checkpoint: run the class again. Three tests pass.

get(..) and when() here are static methods on RestAssured. They need their own static imports, io.restassured.RestAssured.get and io.restassured.RestAssured.when, next to given.

Store the Parts in Variables

given() and get(..) both return ordinary objects, so you can keep either one in a variable.

Keep the Request in a Variable

Goal: build the request in one statement and send it in another.

1
2
3
4
5
6
7
8
@Test
void theRequestSpecificationIsAnOrdinaryObject() {
    RequestSpecification request = given()
        .baseUri(api.baseUri())
        .port(api.port());

    request.when().get("/api/health").then().statusCode(200);
}

What’s happening:

  • given().baseUri(..).port(..) returns a RequestSpecification, which goes into the request variable.
  • request.when().get(..) sends it later, from a separate statement.

This is the first step towards the reusable specifications of Module 5. Later sections of this module already use a small helper method that returns a configured RequestSpecification.

Checkpoint: run the class again. Four tests pass.

Keep the Response and Check It Later

Goal: keep the Response in a variable and check it with both REST Assured and JUnit.

This time the chain stops after get(..):

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aResponseCanBeKeptAndCheckedLater() {
    Response response = given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/health");

    response.then().statusCode(200);

    assertEquals(200, response.statusCode());
    assertEquals("UP", response.path("status"));
}

What’s happening:

  • get(..) returns a Response, which goes into the response variable instead of straight into then().
  • response.then() gives you the same ValidatableResponse as the chained form.
  • response.statusCode() reads the status code as an int.
  • response.path("status") reads a value with the same path language as body(..), so you can check it with JUnit’s assertEquals or any other assertion library.

Store a Response when you need its values, for example to use an id from one response in the next request, or to check it with AssertJ.

Checkpoint: run the class again. Five tests pass.

Extracting values from a response, including typed objects and JSON paths, is covered in depth in Module 4.

Fill a Path Parameter

Most real endpoints have a variable part, such as an account id.

Request an Account by Id

Goal: request one account by filling a {placeholder} in the path.

A path parameter is a {placeholder} in the path that REST Assured fills from the extra arguments of get(..):

1
2
3
4
5
6
7
8
9
10
11
@Test
void pathParametersFillPlaceholdersInTheUrl() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/v1/accounts/{id}", "acc-1001")
    .then()
        .statusCode(200)
        .body("owner", equalTo("Anna de Vries"));
}

What’s happening:

  • "/api/v1/accounts/{id}" declares a placeholder called id.
  • The extra argument, "acc-1001", replaces it, so the request goes to /api/v1/accounts/acc-1001.
  • REST Assured URL-encodes the value, so ids with spaces or special characters still produce a valid URL.
  • body("owner", equalTo("Anna de Vries")) reads the owner field you saw in the response earlier.

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

Don’t build the path by string concatenation, as in .get("/api/v1/accounts/" + id). The value goes into the URL unencoded, and the path is harder to read. Use .get("/api/v1/accounts/{id}", id) and let REST Assured fill it.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-01 -Dtest=GivenWhenThenTest

You should see a result similar to the following:

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

Make a Test Fail

Change assertEquals("UP", response.path("status")) to assertEquals("DOWN", response.path("status")) in aResponseCanBeKeptAndCheckedLater and run the command again. You should see a result similar to the following:

1
2
[ERROR] Failures:
[ERROR]   GivenWhenThenTest.aResponseCanBeKeptAndCheckedLater:89 expected: <DOWN> but was: <UP>

This time the message comes from JUnit, not REST Assured. It shows the expected and actual values, but unlike body("status", ..) in the previous section, it doesn’t name the JSON path that was read.

Change "DOWN" back to "UP" and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
java.net.ConnectException: Connection refusedA chain without given() uses a relative path, so the request goes to port 8080Use the absolute healthUrl, or add given().baseUri(..).port(..)
cannot find symbol: method get(String) or method when()The static import for RestAssured.get or RestAssured.when is missingAdd import static io.restassured.RestAssured.get; and import static io.restassured.RestAssured.when;
expected: <200> but was: <404> on the account testThe placeholder name and the path don’t match, or the id is misspelledCheck that the path is /api/v1/accounts/{id} and the id is acc-1001

Try It Yourself

Exercise 1: Request Another Account

Account acc-1004 belongs to "Emily Clarke". Add a test called pathParameterFindsAnotherAccount that requests it with a path parameter and checks the status code and the owner field.

Hint

Copy pathParametersFillPlaceholdersInTheUrl. Change only the path parameter value and the expected owner.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void pathParameterFindsAnotherAccount() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/v1/accounts/{id}", "acc-1004")
    .then()
        .statusCode(200)
        .body("owner", equalTo("Emily Clarke"));
}

Exercise 2: Store an Account Response

A request to GET /api/v1/accounts/acc-1002 returns a response body similar to the following:

1
2
3
4
5
6
7
8
9
10
{
    "id": "acc-1002",
    "iban": "NL69INGB0123456789",
    "owner": "Anna de Vries",
    "type": "SAVINGS",
    "currency": "EUR",
    "balance": 15000.00,
    "status": "ACTIVE",
    "openedOn": "2021-03-15"
}

Add a test called aStoredAccountResponseCanBeCheckedLater. Request the account with a path parameter and keep the Response in a variable. Then check the status code with response.then(), and check the id and type fields with assertEquals.

Hint

Start from aResponseCanBeKeptAndCheckedLater, and replace "/api/health" with the path parameter form from pathParametersFillPlaceholdersInTheUrl.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void aStoredAccountResponseCanBeCheckedLater() {
    Response response = given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/v1/accounts/{id}", "acc-1002");

    response.then().statusCode(200);

    assertEquals("acc-1002", response.path("id"));
    assertEquals("SAVINGS", response.path("type"));
}

Summary

You built GivenWhenThenTest, which writes the same health check in five forms and requests an account with a path parameter. Your teammate’s three tests now read as one chain: given() builds a RequestSpecification, an HTTP method sends it and returns a Response, and then() turns that into a ValidatableResponse.

  • when() and and() are syntactic sugar: they return the object they were called on and change nothing.
  • An absolute URL lets you leave out given(), and the static get(..) sends a request on one line.
  • A RequestSpecification is an ordinary object, so you can build a request in one place and send it in another.
  • A Response can be kept in a variable and checked later, with REST Assured or any assertion library.
  • A path parameter such as {id} is filled from the extra arguments of get(..) and URL-encoded for you.

Here are the commands you used in this guide:

1
mvn test -pl module-01 -Dtest=GivenWhenThenTest

What’s Next

Next: continue with Control Where REST Assured Requests Go, which shows how a URL is built from baseUri, port, basePath and the path.

The code:

Go deeper:

Related guides:

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