QA and Test Automation · Lab 10 of 35

REST Assured API Test Suite in Java: ShopRung, Step by Step

Build the Java API suite SDET teams build: Maven, JUnit 5 and REST Assured, a shared request spec, a login helper per user, given/when/then checks, parameterized boundaries, records for typed responses, two-user authorisation tests and logging only on failure. 21 tests that catch 7 ShopRung bugs.

⏱ 75 minIntermediate💸 Free8 steps

Java 21Maven 3.9JUnit 5.11REST Assured 5.5Jackson 2.18ShopRung

Overview video

1 / 6

0 of 8 steps done

What you will build

A Maven project that tests ShopRung's API in Java, with 21 tests in three classes on top of two shared helpers:

  • ShopRung: the base URL from -DbaseUrl or BASE_URL, one request spec, the practice users, reset(), and as(User.ALICE), which logs in through the API and returns a spec that sends the token.
  • ApiTest: the base class: a clear message if ShopRung is down, and a reset before every test.
  • AuthApiTest: logins, the same message for a wrong password and an unknown email, missing and tampered tokens.
  • CartApiTest: quantity limits, out of stock, SAVE10 at exactly $50.00 read into a Cart record, FLAT5, expired and unknown coupons, free shipping.
  • OrdersApiTest: stock after an order, the state machine, only admins ship, Bob cannot see Alice's order.

Prefer Python? The pytest API suite builds the same suite with pytest and httpx.

Before you start

Setup

S1Start ShopRung

Start ShopRung as in lab 1 with npm start, and leave that terminal open.

Run
curl http://localhost:8080/api/health
You should see
{"status":"UP","app":"ShopRung","version":"1.0.0"}

S2Check Java 21 and Maven

Both come from lab 4. The Java version line of mvn -v must start with 21.

Run
java -version
mvn -v
You should seeyour text will differ: the model writes it
openjdk version "21.0.x" ...
Apache Maven 3.9.x ...
Java version: 21.0.x, ...

S3Make the project folders

Tests live under src/test/java, in folders that follow the package name dev.algorung.api.

Run
mkdir -p shoprung-rest-assured/src/test/java/dev/algorung/api
cd shoprung-rest-assured
1

The pom.xml: JUnit 5, REST Assured and Jackson

A Maven project with three test libraries at pinned versions.

Create pom.xml in the project folder. Next to JUnit 5, two libraries are new: REST Assured, which sends HTTP requests and checks responses in a given / when / then style, and Jackson, which turns Java maps and records into JSON and back. All three have test scope: they are only for tests.

Versions are properties at the top, so upgrading one is a one-line change in a pull request.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>dev.algorung</groupId>
  <artifactId>shoprung-rest-assured</artifactId>
  <version>0.1.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>5.11.4</junit.version>
    <rest-assured.version>5.5.0</rest-assured.version>
    <jackson.version>2.18.2</jackson.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>${rest-assured.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.13.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.2</version>
      </plugin>
    </plugins>
  </build>
</project>
  1. One place for each version.line 14
  2. Brings Hamcrest too: the equalTo, matchesPattern matchers.line 27
  3. Lets REST Assured send a Map as a JSON body and read a response into a record.line 33
2

Shared settings: the ShopRung helper

One class that knows where ShopRung is, who the users are, and how to log them in.

Create ShopRung.java. Everything every test needs lives here once:

  • BASE_URL comes from -DbaseUrl=... on the Maven command line, or the BASE_URL environment variable, with ShopRung on localhost as the default. One suite, any environment.
  • SHOP is a request specification: base URI and JSON content type, built once. Every request starts with given().spec(SHOP).
  • The static block turns on logging only when a check fails: green runs stay quiet, red runs print the full request and response.
  • tokenFor(user) logs in through the API and extracts the token with a JSON path. as(user) builds a spec that also sends Authorization: Bearer <token>.
src/test/java/dev/algorung/api/ShopRung.java
package dev.algorung.api;

import static io.restassured.RestAssured.given;

import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.util.Map;

/** Everything the tests share: where ShopRung is, the practice accounts, and logged-in request specs. */
public final class ShopRung {
    /** -DbaseUrl=... or the BASE_URL environment variable, else ShopRung on this computer. */
    public static final String BASE_URL = System.getProperty("baseUrl",
            System.getenv().getOrDefault("BASE_URL", "http://localhost:8080"));

    /** Logs the request and the response only when a check fails: quiet when green, detailed when red. */
    static {
        RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
    }

    public static final RequestSpecification SHOP = new RequestSpecBuilder()
            .setBaseUri(BASE_URL)
            .setContentType(ContentType.JSON)
            .build();

    public enum User {
        ALICE("alice@shoprung.test", "Alice123!"),
        BOB("bob@shoprung.test", "Bob12345!"),
        ADMIN("admin@shoprung.test", "Admin123!");

        final String email;
        final String password;

        User(String email, String password) {
            this.email = email;
            this.password = password;
        }
    }

    private ShopRung() {}

    /** Puts ShopRung back to its seed data. */
    public static void reset() {
        given().spec(SHOP).when().post("/api/test/reset").then().statusCode(200);
    }

    /** Logs in through the API and returns the token. */
    public static String tokenFor(User user) {
        return given().spec(SHOP)
                .body(Map.of("email", user.email, "password", user.password))
                .when().post("/api/auth/login")
                .then().statusCode(200)
                .extract().path("token");
    }

    /** A request spec that sends this user's token: given().spec(as(User.ALICE)). */
    public static RequestSpecification as(User user) {
        return new RequestSpecBuilder()
                .addRequestSpecification(SHOP)
                .addHeader("Authorization", "Bearer " + tokenFor(user))
                .build();
    }
}
  1. mvn test -DbaseUrl=https://staging... points every test elsewhere.line 14
  2. The log you need in CI, only when you need it.line 19
  3. Shared settings, built once.line 22
  4. A JSON path into the response body.line 54
  5. Every request built from this spec carries the user's token.line 61
Why this way? Without this class, the base URL, the passwords and the login steps would be copied into every test, and a change would mean editing dozens of files.
3

A base class and the first test

ApiTest fails fast if ShopRung is down and resets it before every test; one login test passes.

Create ApiTest.java. Every test class will extend it. @BeforeAll checks ShopRung's health once per class with the JDK's own HTTP client and stops with one clear message if the shop is not running. @BeforeEach resets the shop before every test, so tests never depend on each other.

Then create AuthApiTest.java with one test. Read it out loud: given the shop spec and a body with Alice's login, when you post to the login endpoint, then the status is 200 and the token matches the shape of a JWT, three parts separated by dots. A Map becomes the JSON body automatically.

src/test/java/dev/algorung/api/ApiTest.java
package dev.algorung.api;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;

/** The base class for every API test: ShopRung must be up, and each test starts from the seed data. */
abstract class ApiTest {
    @BeforeAll
    static void shopRungIsRunning() {
        try {
            HttpClient.newHttpClient().send(
                    HttpRequest.newBuilder(URI.create(ShopRung.BASE_URL + "/api/health")).build(),
                    HttpResponse.BodyHandlers.discarding());
        } catch (Exception e) {
            throw new IllegalStateException(
                    "ShopRung is not running at " + ShopRung.BASE_URL + ". Start it with: npm start", e);
        }
    }

    @BeforeEach
    void resetShop() {
        ShopRung.reset();
    }
}
  1. Once per class: is the shop up?line 12
  2. One readable reason instead of 21 connection errors.line 19
  3. Known data in, known results out.line 24
src/test/java/dev/algorung/api/AuthApiTest.java
package dev.algorung.api;

import static dev.algorung.api.ShopRung.SHOP;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.matchesPattern;

import java.util.Map;
import org.junit.jupiter.api.Test;

/** ACC rules: who you are (401) is tested apart from what you may do (403/404). */
class AuthApiTest extends ApiTest {
    @Test
    void loginReturnsAToken() {
        given().spec(SHOP)
                .body(Map.of("email", "alice@shoprung.test", "password", "Alice123!"))
        .when()
                .post("/api/auth/login")
        .then()
                .statusCode(200)
                .body("token", matchesPattern("[^.]+\\.[^.]+\\.[^.]+")); // a JWT has three parts
    }
}
  1. Serialized to JSON by Jackson.line 15
  2. Then: the checks. Each one names what failed.line 19
  3. A Hamcrest matcher on the token field.line 5
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Running dev.algorung.api.AuthApiTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
...
[INFO] BUILD SUCCESS
Stuck on this step?
ShopRung is not running at http://localhost:8080
Start it with npm start in its folder, or run mvn test -DbaseUrl=http://localhost:PORT.
The first run takes minutes.
Maven downloads REST Assured and its dependencies once. Later runs take seconds.
4

Auth rules: bad logins and tokens

Six tests for ShopRung's login rules, including a parameterized one and a tampered token.

Replace AuthApiTest.java. Four tests are new:

  • @ParameterizedTest with @CsvSource runs one method per row: a wrong password and an unknown email. Both must return 401 with exactly Email or password is wrong, so attackers cannot tell which emails have accounts.
  • Emails are not case sensitive: ALICE@shoprung.test logs in.
  • No token on /api/cart is 401 unauthorized.
  • A real token with its last character changed: the signature no longer matches, so 401 invalid_token.
src/test/java/dev/algorung/api/AuthApiTest.java 27 new or changed lines
package dev.algorung.api;

import static dev.algorung.api.ShopRung.SHOP;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;

import dev.algorung.api.ShopRung.User;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

/** ACC rules: who you are (401) is tested apart from what you may do (403/404). */
class AuthApiTest extends ApiTest {
    @Test
    void loginReturnsAToken() {
        given().spec(SHOP)
                .body(Map.of("email", "alice@shoprung.test", "password", "Alice123!"))
        .when()
                .post("/api/auth/login")
        .then()
                .statusCode(200)
                .body("token", matchesPattern("[^.]+\\.[^.]+\\.[^.]+")); // a JWT has three parts
    }

    @ParameterizedTest(name = "{0} / {1} -> the same message")
    @CsvSource({
        "alice@shoprung.test,  wrong",      // wrong password
        "nobody@shoprung.test, Alice123!",  // unknown email
    })
    void badLoginGivesTheSameMessage(String email, String password) {
        given().spec(SHOP)
                .body(Map.of("email", email, "password", password))
        .when()
                .post("/api/auth/login")
        .then()
                .statusCode(401)
                .body("message", equalTo("Email or password is wrong"));
    }

    @Test
    void emailIsNotCaseSensitive() {
        given().spec(SHOP)
                .body(Map.of("email", "ALICE@shoprung.test", "password", "Alice123!"))
        .when()
                .post("/api/auth/login")
        .then()
                .statusCode(200);
    }

    @Test
    void cartNeedsAToken() {
        given().spec(SHOP)
        .when()
                .get("/api/cart")
        .then()
                .statusCode(401)
                .body("error", equalTo("unauthorized"));
    }

    @Test
    void aTamperedTokenIsRefused() {
        String token = ShopRung.tokenFor(User.ALICE);
        String tampered = token.substring(0, token.length() - 1) + (token.endsWith("A") ? "B" : "A");
        given().spec(SHOP)
                .header("Authorization", "Bearer " + tampered)
        .when()
                .get("/api/cart")
        .then()
                .statusCode(401)
                .body("error", equalTo("invalid_token"));
    }
}
  1. The name template makes each row readable in the report.line 27
  2. Unknown email: must look exactly like a wrong password.line 30
  3. Change one character: a forged token must be refused.line 65
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
5

Cart boundaries, logged in as Alice

Quantity limits and an out of stock product, with a per-test login.

Create CartApiTest.java. Its own @BeforeEach logs Alice in with ShopRung.as(User.ALICE). JUnit runs the parent's @BeforeEach first, so the reset always happens before the login.

The add helper returns REST Assured's ValidatableResponse, so each test continues with its own checks. Quantities 0 and 11 are refused (400), 1 and 10 accepted. The Red Build Mug has no stock: 409, Red Build Mug is out of stock.

src/test/java/dev/algorung/api/CartApiTest.java
package dev.algorung.api;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import dev.algorung.api.ShopRung.User;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

/** CART and PRICE rules on their boundaries. Products: 1 = notebook $12.50, 6 = T-shirt $20.00, 8 = keyboard $75.00. */
class CartApiTest extends ApiTest {
    private RequestSpecification alice;

    @BeforeEach
    void logInAsAlice() {
        alice = ShopRung.as(User.ALICE); // runs after the reset in ApiTest
    }

    private ValidatableResponse add(long productId, int quantity) {
        return given().spec(alice)
                .body(Map.of("productId", productId, "quantity", quantity))
                .when().post("/api/cart/items")
                .then();
    }

    @ParameterizedTest(name = "quantity {0} -> {1}")
    @CsvSource({"0, 400", "1, 200", "10, 200", "11, 400"})
    void quantityMustBe1To10(int quantity, int status) {
        add(1, quantity).statusCode(status);
    }

    @Test
    void outOfStockProductCannotBeAdded() {
        add(5, 1).statusCode(409).body("message", equalTo("Red Build Mug is out of stock"));
    }
}
  1. A fresh login per test: no state leaks between tests.line 21
  2. A tiny helper keeps each test to the point.line 24
  3. Both sides of both edges.line 32
Run
mvn test -Dtest=CartApiTest
You should seeyour text will differ: the model writes it
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
6

Coupons and shipping, with a typed Cart record

SAVE10 at exactly $50.00 read into a record, FLAT5, coupons that do not apply, and free shipping.

Create Cart.java: a record with the fields the tests read. @JsonIgnoreProperties(ignoreUnknown = true) means a new field in the API does not break the tests. Then replace CartApiTest.java.

The SAVE10 test adds four notebooks ($50.00, the lowest subtotal SAVE10 accepts), applies save10 in lower case, and reads the response with extract().as(Cart.class). Now the checks are typed: cart.totalCents() is a long, and the compiler catches typos. assertAll runs all five checks and reports every one that fails, not just the first.

Other tests use JSON paths directly, which is fine for one or two fields: FLAT5 at $20.00 makes $19.99, WELCOME15 is expired (400), NOPE is unknown (404), and one $75.00 keyboard ships free.

src/test/java/dev/algorung/api/Cart.java
package dev.algorung.api;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;

/** The parts of ShopRung's cart response the tests read. Unknown fields are ignored, so new ones break nothing. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record Cart(List<Line> items, int itemCount, long subtotalCents, long discountCents,
                   long shippingCents, long totalCents, String total) {

    @JsonIgnoreProperties(ignoreUnknown = true)
    public record Line(long productId, String sku, int quantity, long lineCents) {}
}
  1. Tolerant of new fields, strict about the ones you read.line 7
  2. Nested records for the list of items.line 12
src/test/java/dev/algorung/api/CartApiTest.java 30 new or changed lines
package dev.algorung.api;

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

import dev.algorung.api.ShopRung.User;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

/** CART and PRICE rules on their boundaries. Products: 1 = notebook $12.50, 6 = T-shirt $20.00, 8 = keyboard $75.00. */
class CartApiTest extends ApiTest {
    private RequestSpecification alice;

    @BeforeEach
    void logInAsAlice() {
        alice = ShopRung.as(User.ALICE); // runs after the reset in ApiTest
    }

    private ValidatableResponse add(long productId, int quantity) {
        return given().spec(alice)
                .body(Map.of("productId", productId, "quantity", quantity))
                .when().post("/api/cart/items")
                .then();
    }

    private ValidatableResponse coupon(String code) {
        return given().spec(alice).body(Map.of("code", code)).when().post("/api/cart/coupon").then();
    }

    @ParameterizedTest(name = "quantity {0} -> {1}")
    @CsvSource({"0, 400", "1, 200", "10, 200", "11, 400"})
    void quantityMustBe1To10(int quantity, int status) {
        add(1, quantity).statusCode(status);
    }

    @Test
    void outOfStockProductCannotBeAdded() {
        add(5, 1).statusCode(409).body("message", equalTo("Red Build Mug is out of stock"));
    }

    @Test
    void save10AppliesAtExactly50Dollars() {
        add(1, 4).statusCode(200); // 4 x $12.50 = $50.00
        Cart cart = coupon("save10").statusCode(200).extract().as(Cart.class);
        assertAll(
                () -> assertEquals(5000, cart.subtotalCents(), "subtotal"),
                () -> assertEquals(500, cart.discountCents(), "discount"),
                () -> assertEquals(499, cart.shippingCents(), "shipping"),
                () -> assertEquals(4999, cart.totalCents(), "total"),
                () -> assertEquals("$49.99", cart.total(), "total as shown"));
    }

    @Test
    void flat5AtExactly20Dollars() {
        add(6, 1).statusCode(200);
        coupon("FLAT5").statusCode(200)
                .body("discountCents", equalTo(500))
                .body("totalCents", equalTo(1999));
    }

    @ParameterizedTest(name = "{0} -> {1}")
    @CsvSource({
        "WELCOME15, 400, This coupon has expired",
        "NOPE,      404, No coupon called NOPE",
    })
    void couponsThatDoNotApply(String code, int status, String message) {
        add(6, 1).statusCode(200);
        coupon(code).statusCode(status).body("message", equalTo(message));
    }

    @Test
    void shippingIsFreeFrom75Dollars() {
        add(8, 1).statusCode(200)            // exactly $75.00
                .body("shippingCents", equalTo(0))
                .body("totalCents", equalTo(7500));
    }
}
  1. JSON to a record, through Jackson.line 51
  2. All five numbers checked and reported together.line 52
  3. Status AND message: two different failures, two different codes.line 71
Run
mvn test -Dtest=CartApiTest
You should seeyour text will differ: the model writes it
[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
7

Orders: side effects, roles and a second user

Five order tests that look past the response.

Create OrdersApiTest.java:

  • Stock. Ordering 2 copies of The Bug Hunter's Diary must reduce its stock by 2 and empty the cart. The order response cannot tell you that, so the test reads the product and the cart again.
  • Empty cart. Ordering nothing is 400 empty_cart.
  • State machine. Alice's seed order 2 is SHIPPED: cancelling it is 409, Cannot cancel an order that is SHIPPED.
  • Roles. Alice pays for her order, but shipping it as a customer is 403; the admin can, and the status becomes SHIPPED.
  • Ownership. Bob asks for Alice's order 1: 404, No order with id 1. Always test with a second user.
src/test/java/dev/algorung/api/OrdersApiTest.java
package dev.algorung.api;

import static dev.algorung.api.ShopRung.SHOP;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;

import dev.algorung.api.ShopRung.User;
import io.restassured.specification.RequestSpecification;
import java.util.Map;
import org.junit.jupiter.api.Test;

/** ORD rules: placing, stock, the state machine and who may see an order. */
class OrdersApiTest extends ApiTest {

    private static int stockOf(int productId) {
        return given().spec(SHOP).when().get("/api/products/" + productId)
                .then().statusCode(200).extract().path("stock");
    }

    /** Adds the product and places the order; returns the new order's id. */
    private static int place(RequestSpecification user, int productId, int quantity) {
        given().spec(user).body(Map.of("productId", productId, "quantity", quantity))
                .when().post("/api/cart/items").then().statusCode(200);
        return given().spec(user).when().post("/api/orders")
                .then().statusCode(201).body("status", equalTo("PLACED"))
                .extract().path("id");
    }

    @Test
    void placingAnOrderReducesStockAndEmptiesTheCart() {
        RequestSpecification alice = ShopRung.as(User.ALICE);
        int before = stockOf(3); // The Bug Hunter's Diary
        place(alice, 3, 2);
        assertEquals(before - 2, stockOf(3), "stock after ordering 2");
        given().spec(alice).when().get("/api/cart").then().body("itemCount", equalTo(0));
    }

    @Test
    void anEmptyCartCannotBeOrdered() {
        given().spec(ShopRung.as(User.ALICE)).when().post("/api/orders")
                .then().statusCode(400).body("error", equalTo("empty_cart"));
    }

    @Test
    void aShippedOrderCannotBeCancelled() {
        given().spec(ShopRung.as(User.ALICE)).when().post("/api/orders/2/cancel") // seed order 2 is SHIPPED
                .then().statusCode(409).body("message", equalTo("Cannot cancel an order that is SHIPPED"));
    }

    @Test
    void onlyAnAdminCanShip() {
        RequestSpecification alice = ShopRung.as(User.ALICE);
        int id = place(alice, 1, 1);
        given().spec(alice).when().post("/api/orders/" + id + "/pay").then().statusCode(200);
        given().spec(alice).when().post("/api/orders/" + id + "/ship").then().statusCode(403);
        given().spec(ShopRung.as(User.ADMIN)).when().post("/api/orders/" + id + "/ship")
                .then().statusCode(200).body("status", equalTo("SHIPPED"));
    }

    @Test
    void bobCannotSeeAlicesOrder() {
        given().spec(ShopRung.as(User.BOB)).when().get("/api/orders/1")
                .then().statusCode(404).body("message", equalTo("No order with id 1"));
    }
}
  1. Read the stock before and after, instead of trusting the seed number.line 16
  2. The side effect. A 201 alone proves nothing here.line 35
  3. Two users in one test: each spec has its own token.line 57
  4. Broken object-level authorisation is the top API risk.line 63
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 -- in dev.algorung.api.AuthApiTest
[INFO] Tests run: 10, Failures: 0, Errors: 0, Skipped: 0 -- in dev.algorung.api.CartApiTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 -- in dev.algorung.api.OrdersApiTest
[INFO] Tests run: 21, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
8

Run it like CI does

One class, one method, another server, and the reports Maven writes.

-Dtest=Class#method runs a single test while you work on it. -DbaseUrl points the whole suite at another server. Surefire writes JUnit XML reports to target/surefire-reports/, which every CI server can display, so a pipeline only needs mvn test. Part 8 runs this in GitHub Actions.

Run
mvn test -Dtest=OrdersApiTest#bobCannotSeeAlicesOrder
mvn test -DbaseUrl=http://localhost:8080
ls target/surefire-reports
You should seeyour text will differ: the model writes it
TEST-dev.algorung.api.AuthApiTest.xml
TEST-dev.algorung.api.CartApiTest.xml
TEST-dev.algorung.api.OrdersApiTest.xml
...

Check it works

Switch on ShopRung's coupon-boundary bug and run the suite. Only save10AppliesAtExactly50Dollars fails: the shop answers 400 where the rule says 200, and because logging is on for failures, the output shows the full request and the response body with the reason.

Then try each of quantity-limit, free-shipping-boundary, cancel-shipped, stock-not-reduced, expired-coupon and order-leak: each one fails exactly one test. Finally switch on mystery mode: five tests fail, one per hidden bug. Turn the bugs off at the end.

Test
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["coupon-boundary"]}'
mvn test
You should see
Request method:	POST
Request URI:	http://localhost:8080/api/cart/coupon
...
HTTP/1.1 400 Bad Request
...
[ERROR] CartApiTest.save10AppliesAtExactly50Dollars:... 1 expectation failed.
Expected status code <200> but was <400>.
...
[ERROR] Tests run: 21, Failures: 1, Errors: 0, Skipped: 0

Troubleshooting

Cannot serialize object because no JSON serializer found

Jackson is missing. Check the jackson-databind dependency is in pom.xml and run mvn test again.

UnrecognizedPropertyException when reading the Cart record.

Add @JsonIgnoreProperties(ignoreUnknown = true) to the record (and to nested records): the response has fields the record does not list.

Every test fails with Connection refused.

ShopRung is not running on the base URL. Start it, or pass -DbaseUrl=http://localhost:PORT.

Tests pass alone but fail together.

A test class does not extend ApiTest, so the reset does not run before its tests.

No tests were executed!

Test classes must end in Test (Surefire's default pattern) and live under src/test/java.

What changes in production

  • Real suites keep a helper like ShopRung as the API client layer, often with one class per resource (users, carts, orders), so tests read like the domain.
  • Credentials come from CI secrets; base URLs come from properties per environment.
  • Data is created per test (a new user through the API) instead of a global reset, which lets JUnit run tests in parallel.
  • Reports go to CI from target/surefire-reports, often through Allure for steps and attached request logs (Part 7).

Interview angle

“How do you structure a REST Assured framework?”

A client layer holds the base URL from configuration, a shared RequestSpecification with JSON and logging on failure, and a login helper that returns a spec with the user's bearer token. A base test class checks the environment and prepares data. Tests use given/when/then, check status plus exact values through JSON paths or records with Jackson, parameterize boundaries, and include side effects and two-user authorisation checks. Maven runs them anywhere with -DbaseUrl, and Surefire's XML reports feed CI. I prove the suite by planting bugs and seeing the right test fail.

Clean up

Practice

These run in your browser and check your answer.

A JSON path, by hand

REST Assured reads values with paths like items[0].sku. Write get_path(data, path) that follows a dotted path through nested dicts and lists: a part like items[0] means "key items, then index 0". get_path({"items": [{"sku": "BK-101"}]}, "items[0].sku") returns "BK-101".

Exercise
def get_path(data, path):
    value = data
    for part in path.split("."):
        value = value[part]  # does not handle [0] yet
    return value
Hint

Split a part like "items[1]" into the name and the number: part.split("[") gives ["items", "1]"].

The full project

Every file from this lab, as it is after the last step.

Download Java project (.zip)