Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 66 ยท Testing

API Tests with REST Assured

Write readable black-box HTTP and JSON tests for a running Spring Boot app with REST Assured's given-when-then style, plus a note on ZeroCode and when to choose each tool.

MockMvc tests a controller inside the application without a real network. Sometimes you want the opposite: to treat the application as a black box, start it on a real port, and talk to it over HTTP exactly like a client would. You then check status codes, headers and JSON bodies without knowing anything about controllers or beans. That style is called API testing, and REST Assured is the most widely used Java library for it.

This lesson shows how REST Assured reads and how to combine it with @SpringBootTest, then rebuilds a miniature version in plain Java so you can run something real: a small HTTP server on 127.0.0.1, a tiny given().when().then() DSL and a few API tests. The REST Assured code itself is read-only, because that library is not on this site's runner. The demo says clearly what is real (real HTTP and real JSON parsing) and what is the stand-in (the DSL and the server).

Where API tests fit

Test style Starts Talks over Good for
Unit test Nothing Method calls Business rules
MockMvc / @WebMvcTest Web slice In-memory dispatch Controller mappings, validation, JSON shape
@SpringBootTest + REST Assured Whole app on a random port Real HTTP Serialization, filters, security, error format end to end
External API tests (REST Assured or ZeroCode against a deployed URL) Nothing (app already deployed) Real HTTP Smoke tests after a release

A few API tests of the critical flows complement a large base of faster tests; see the testing pyramid in Testing Fundamentals.

REST Assured in a Spring Boot test

Add the dependency in test scope (Spring Boot manages the version):

XML
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <scope>test</scope>
</dependency>

Start the application on a random port and point REST Assured at it:

Java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class BookApiTest {

    @LocalServerPort
    int port;

    @BeforeEach
    void setUp() {
        RestAssured.baseURI = "http://localhost";
        RestAssured.port = port;
    }

    @Test
    void listsBooks() {
        given()
            .accept(ContentType.JSON)
        .when()
            .get("/api/books")
        .then()
            .statusCode(200)
            .contentType(ContentType.JSON)
            .body("size()", greaterThan(0))
            .body("[0].title", notNullValue());
    }

    @Test
    void createsABook() {
        given()
            .contentType(ContentType.JSON)
            .body("""
                {"title": "Refactoring", "priceInCents": 4500}
                """)
        .when()
            .post("/api/books")
        .then()
            .statusCode(201)
            .header("Location", containsString("/api/books/"))
            .body("title", equalTo("Refactoring"))
            .body("id", notNullValue());
    }

    @Test
    void rejectsInvalidInput() {
        given()
            .contentType(ContentType.JSON)
            .body("{\"title\": \"\", \"priceInCents\": -1}")
        .when()
            .post("/api/books")
        .then()
            .statusCode(400)
            .body("errors.title", hasItem("must not be blank"));
    }
}

The three blocks mean given (the request you prepare), when (the call) and then (the checks). The assertions inside .body(...) use Hamcrest matchers (equalTo, hasItem, containsString). Paths such as "[0].title" or "errors.title" are Groovy-style JsonPath expressions evaluated against the response.

Things you will do often

  • Authentication. given().auth().oauth2(token) sends a bearer token; .auth().basic(user, pass) sends basic credentials. Get a token from your login endpoint in a helper method, or from a test JWT.
  • Extract values to reuse them in a follow-up call: String id = given()...post(...).then().extract().path("id");.
  • Whole-body checks: .extract().as(BookResponse.class) deserializes into your DTO, so you can use normal assertions.
  • Schema validation: the json-schema-validator module checks a body against a JSON Schema file, which catches accidental contract changes.
  • Logging on failure: .log().ifValidationFails() prints the request and response only when a check fails.
  • Reuse: put common settings (base path, content type, auth) in a RequestSpecification built once and passed with given().spec(spec).

Tests that call a real server share state through the database. Give each test its own data (create what you need at the start), or reset the database between tests, as in Testing the Data Layer. Use Testcontainers when you want the real database engine as well.

A miniature given/when/then in plain Java

REST Assured is a thin, readable layer over HTTP. To see what happens underneath, the demo below builds a small version: a real com.sun.net.httpserver.HttpServer on a random loopback port plays the application, java.net.http.HttpClient sends real requests, Jackson parses the JSON, and a few classes provide given(), when() and then(). Paths use JSON Pointer (/0/title) where real REST Assured uses [0].title. Each test reports PASS or FAIL, and the last one fails on purpose so you can see an assertion message.

Java A tiny REST Assured, a real server and four API tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at how little the real library needs to do: build a request, send it, parse the body, compare. What REST Assured adds is a mature, readable vocabulary (Hamcrest matchers, GPath expressions, specs, auth helpers, logging) so you do not have to write that plumbing for every project.

Choosing a tool

Need Tool
Fluent HTTP tests written in Java, with the app started by the same test REST Assured with @SpringBootTest
Test controllers without a network, fast MockMvc or RestTestClient (see MockMvc and Web Tests)
Test scenarios declared as JSON files, with no Java code per test ZeroCode
Contract testing between teams Spring Cloud Contract or Pact

ZeroCode takes a different approach: a scenario is a JSON file describing the request and the expected response, and a small JUnit class runs it:

JSON
{
  "scenarioName": "Create and fetch a book",
  "steps": [
    {
      "name": "create",
      "url": "/api/books",
      "method": "POST",
      "request": { "body": { "title": "Refactoring" } },
      "verify": {
        "status": 201,
        "body": { "title": "Refactoring", "id": "$NOT.NULL" }
      }
    }
  ]
}
Java
@RunWith(ZeroCodeUnitRunner.class)   // or the JUnit 5 extension of your version
@TargetEnv("application_host.properties")
@Scenario("scenarios/create_and_fetch_book.json")
class BookScenarioTest {}

It suits teams with testers who prefer declarative files over code, and it can chain steps by reusing values from earlier responses. For most Java teams REST Assured is the simpler default, because tests are ordinary code you can refactor and debug.

Habits for reliable API tests

  • Test behavior, not implementation. Check status, headers and the JSON you promised; avoid asserting on every field of every response.
  • Keep the error format under test. A stable error body (Error Handling) is part of the contract.
  • Cover security explicitly. Anonymous gets 401, wrong role gets 403, correct role succeeds.
  • Make tests independent. Each test creates its own data and does not rely on execution order.
  • Do not duplicate everything. One API test per important flow, with the detailed edge cases in faster unit and slice tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the given-when-then structure in REST Assured represent?

    given() prepares headers, body and auth, when() makes the call, and then() verifies status, headers and body.
  2. 2. Why use webEnvironment = RANDOM_PORT with @LocalServerPort?

    A random port avoids conflicts with other processes or parallel tests, and the injected port value lets the test build correct URLs.
  3. 3. How is an API test with REST Assured different from a MockMvc test?

    REST Assured goes through the real network stack, so servlet filters, serialization and the actual container behavior are all exercised.
  4. 4. Which statement about ZeroCode is right?

    ZeroCode favors declarative JSON scenarios, which suits teams who want tests without writing Java for each case.
  5. 5. What is a good use of a small number of API tests?

    They are slower and heavier than unit tests, so use them for the flows and contracts that matter most.

Summary

  • API tests treat the application as a black box and talk to it over real HTTP; REST Assured gives them a fluent given/when/then style.
  • With @SpringBootTest(webEnvironment = RANDOM_PORT) and @LocalServerPort, tests start the app and point REST Assured at the right port.
  • Check status codes, headers and JSON bodies with matchers, extract values for follow-up calls and share settings with request specifications.
  • ZeroCode offers a declarative alternative with JSON scenarios; MockMvc is the faster in-process option.
  • Keep API tests few and meaningful, independent of each other, and focused on contracts, security and error formats.

Next: Code Coverage with JaCoCo.