Post

Test a Spring Controller With RestAssuredMockMvc in Standalone Mode

Test a Spring MVC controller with REST Assured's syntax and no server, no socket and no Spring context, using RestAssuredMockMvc's standaloneSetup(..), and learn what that mode leaves out.

Test a Spring Controller With RestAssuredMockMvc in Standalone Mode

Every API in this guide so far ran on a real HTTP server, started by the test. A Spring Boot application can be tested that way too, and section 3 of this module does. But starting a whole application takes seconds, and for a test that only checks what a controller returns, most of that start-up is wasted. Spring’s MockMvc calls the controller through Spring MVC with no network at all, and REST Assured’s spring-mock-mvc module puts the familiar given().when().then() on top of it. In this guide, you’ll test a controller you build yourself, with no server and no Spring context, and learn what that leaves out.

Level: Advanced · Time: 20 minutes · Part of: Module 11: Spring Boot Integration, section 1

What You’ll Build

You’ll build a test class called StandaloneMockMvcTest with five tests for a Spring accounts controller: list the accounts, read one, read an unknown one, open one, and send an invalid one.

The tests look like every REST Assured test so far, with one difference in the first line:

1
2
3
4
5
6
given().standaloneSetup(new AccountController(new AccountService()))
.when()
    .get("/api/v1/accounts")
.then()
    .statusCode(200)
    .body("$", hasSize(2));

When you’re done, Maven reports five passing tests, in about half a second:

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

In this guide, you will:

  • Read accounts through the controller.
  • Open accounts through the controller.
  • See what standalone mode leaves out.

What You Need

How to Complete This Guide

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

  • Build it step by step: this is the first section of Module 11, so you start from scratch. Create StandaloneMockMvcTest in the module-11 test sources and follow every heading below.
  • Skip ahead: open the finished class (StandaloneMockMvcTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: clone the examples repository and change into it:

1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples

If you’ve already cloned it for an earlier module, run git pull instead. The module uses Spring Boot 4.1 and REST Assured’s spring-mock-mvc module.

Out of scope: this guide doesn’t cover Spring Security or Spring Boot’s error handling; they’re taught in section 2 and section 3.

Understand RestAssuredMockMvc

The problem. A full Spring Boot test starts the application, a servlet container and a port, which takes seconds. For many tests, such as routing, JSON conversion and status codes, all of that is overhead.

The concept. RestAssuredMockMvc is REST Assured on top of Spring’s MockMvc:

  • The syntax is the same: given(), when(), then(), body paths and matchers. Only the static import changes, to io.restassured.module.mockmvc.RestAssuredMockMvc.given.
  • There’s no HTTP: MockMvc calls Spring’s DispatcherServlet directly, with mock request and response objects. No server starts, and nothing goes over a socket.
  • There are three set-ups: standaloneSetup(controller) with no Spring context, webAppContextSetup(..) with one, and mockMvc(..) with a MockMvc that Spring built.

In standalone mode, you build the controller yourself, with new. Spring MVC handles routing, JSON conversion and status codes, and nothing else from the application runs:

Part of the applicationStandaloneWeb sliceRandom port
Routing, JSON conversion, status codesYesYesYes
Spring SecurityNoYesYes
Spring Boot problem detailsNoYesYes
Real HTTP, servlet container, token validationNoNoYes
SpeedFastestFastSlowest

When to use each. Use standalone mode for many quick tests of a controller’s own logic: mapping, validation and status codes. Test security and error formats in a web slice or against a running server.

Test the controller’s logic in standalone mode, and nothing it doesn’t contain.

Meet the API Under Test

Module 11 tests a Spring Boot 4.1 accounts service with one controller, AccountController:

RequestAnswer
GET /api/v1/accountsThe accounts, as a JSON array
GET /api/v1/accounts/{id}One account, or 404
POST /api/v1/accounts201 with a Location, or 422 for a missing or invalid IBAN, owner or currency

The in-memory AccountService starts with two accounts, and gives new ones the ids acc-1003, acc-1004 and so on:

1
2
[{"id":"acc-1001","iban":"NL91ABNA0417164300","owner":"Anna de Vries","currency":"EUR","balance":"1250.50"},
 {"id":"acc-1002","iban":"NL69INGB0123456789","owner":"Jan Jansen","currency":"EUR","balance":"15000.00"}]

The controller gets its service through its constructor, which is what makes standalone mode work:

1
2
3
4
5
6
7
8
9
10
11
@RestController
@RequestMapping("/api/v1/accounts")
public class AccountController {

    private final AccountService service;

    public AccountController(AccountService service) {
        this.service = service;
    }
    ...
}

Your tests check these values:

  • The status, the content type and the Location header.
  • The accounts’ owner and balance, as strings.

Read Accounts Through the Controller

Set Up the Test Class

Goal: create the test class with a specification that builds a new controller for every test.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.javanibble.module_11.section_01;

import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;

import com.javanibble.accounts.AccountController;
import com.javanibble.accounts.AccountService;

import io.restassured.http.ContentType;
import io.restassured.module.mockmvc.specification.MockMvcRequestSpecification;

import org.junit.jupiter.api.Test;

class StandaloneMockMvcTest {

    private static MockMvcRequestSpecification accounts() {
        return given().standaloneSetup(new AccountController(new AccountService()));
    }
}

What’s happening:

  • given() comes from RestAssuredMockMvc, and returns a MockMvcRequestSpecification.
  • standaloneSetup(..) takes the controller object, and Spring MVC wraps it in a DispatcherServlet, without a context.
  • Each call builds a new controller with a new service, so every test starts with the same two accounts. There’s no @BeforeAll: nothing needs starting.

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

Import given from RestAssuredMockMvc, not RestAssured. The ordinary RestAssured sends real HTTP: io.restassured.RestAssured.get("/api/v1/accounts") failed with java.net.ConnectException: Connection refused, because no server is listening.

List the Accounts

Goal: read the list, and check its size and first owner.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
@Test
void listAccounts() {
    accounts()
    .when()
        .get("/api/v1/accounts")
    .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .body("$", hasSize(2))
        .body("owner[0]", equalTo("Anna de Vries"));               // "owner" collects the owner of every element
}

What’s happening:

  • The body is a JSON array at the root, so $ is the list.
  • owner collects the owner of every element, and owner[0] takes the first.
  • Spring MVC converted the List<Account> to JSON with Jackson, and set Content-Type: application/json.

Checkpoint: run StandaloneMockMvcTest from your IDE. One test runs and passes, with no server started.

Read One Account

Goal: read one account by id, and an unknown one.

Add these tests to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void readOneAccount() {
    accounts()
    .when()
        .get("/api/v1/accounts/{id}", "acc-1002")
    .then()
        .statusCode(200)
        .body("balance", equalTo("15000.00"));
}

@Test
void anUnknownAccount() {
    accounts().when().get("/api/v1/accounts/{id}", "acc-9999").then().statusCode(404);
}

What’s happening:

  • Path parameters work as with the ordinary RestAssured.
  • For an unknown id, the controller throws ResponseStatusException(NOT_FOUND, "Account acc-9999 does not exist"), and the test checks only the status.
  • That’s all it can check from the body: in standalone mode, the 404 has an empty body and no content type.

Checkpoint: run the class again. Three tests pass.

An unknown route gets the same empty 404 as an unknown account, so a status check can’t tell them apart. The reason is in the status line: here, 404 Account acc-9999 does not exist. Exercise 2 checks it with statusLine(..).

Open Accounts Through the Controller

Open an Account

Goal: open an account, and check its Location and balance.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void openAnAccount() {
    accounts()
        .contentType(ContentType.JSON)
        .body("{\"iban\": \"NL20INGB0001234567\", \"owner\": \"Sanne Smit\", \"currency\": \"EUR\"}")
    .when()
        .post("/api/v1/accounts")
    .then()
        .statusCode(201)
        .header("Location", "/api/v1/accounts/acc-1003")
        .body("balance", equalTo("0.00"));
}

What’s happening:

  • The service is new for this test, so the next id is predictable, and the test checks the exact Location.
  • A new account starts with a balance of 0.00.
  • contentType(ContentType.JSON) is needed: without it, the controller answered 415 Unsupported Media Type.

Checkpoint: run the class again. Four tests pass.

Send an Invalid Account

Goal: prove the controller refuses an account without an IBAN.

Add this test to the class:

1
2
3
4
5
6
7
8
9
10
@Test
void anInvalidAccount() {
    accounts()
        .contentType(ContentType.JSON)
        .body("{\"owner\": \"No IBAN\"}")
    .when()
        .post("/api/v1/accounts")
    .then()
        .statusCode(422);
}

What’s happening:

  • The body has no IBAN or currency, so the controller throws ResponseStatusException(UNPROCESSABLE_CONTENT, "iban, owner and currency are required").
  • As with the 404, the body is empty in standalone mode; the reason is only in the status line.

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

See What Standalone Mode Leaves Out

The controller ran, and so did Spring MVC’s routing and JSON conversion. Nothing else from the application did:

  • No Spring Security. In the real application, reading accounts needs a token with the scope accounts:read. Here, every request succeeds, so a passing test says nothing about who may call the endpoint.
  • No problem details. In the real application, spring.mvc.problemdetails.enabled=true makes Spring Boot turn a ResponseStatusException into an RFC 9457 problem detail. Here, errors have empty bodies.
  • No configuration. Properties, filters and @ControllerAdvice beans from the application don’t exist unless you add them to standaloneSetup(..) yourself.

A passing standalone test doesn’t mean the endpoint is open, or that its errors have bodies. Check security and error formats in a web slice or against the real server, as the next two sections do.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-11 -Dtest=StandaloneMockMvcTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_11.section_01.StandaloneMockMvcTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.482 s -- in com.javanibble.module_11.section_01.StandaloneMockMvcTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In anUnknownAccount, add .body("detail", equalTo("Account acc-9999 does not exist")) after statusCode(404), as you would against the real application, and run the command again. You should see a result similar to the following:

1
2
3
4
5
6
[ERROR] Errors:
[ERROR]   StandaloneMockMvcTest.anUnknownAccount:53 » IllegalState Expected response body to be verified as JSON, HTML or XML but content-type 'null' is not supported out of the box.
Try registering a custom parser using:
   RestAssured.registerParser("null", <parser type>);
Content was:

The body is empty and has no content type, so REST Assured has nothing to parse. This is what “standalone mode leaves out Spring Boot’s problem details” looks like in a test: the check is right for the real application, and impossible here.

Remove the .body(..) check and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
ConnectException: Connection refusedgiven was imported from RestAssured, which sends real HTTPImport RestAssuredMockMvc.given
content-type 'null' is not supported on an errorStandalone mode has no problem details, so the body is emptyCheck the status line, or test errors in a web slice
415 on a POSTNo content type on the requestAdd contentType(ContentType.JSON)
A test sees another test’s accountThe controller or service is shared between testsBuild a new one per test, as accounts() does

Try It Yourself

Exercise 1: Open and Read Back an Account

Add a test called openAndReadBackAnAccount. Open an account, then read it from its Location, and check its owner and balance, and that the list now has three accounts. accounts() builds a new service each time, so a read in a new accounts() call got 404.

Hint

Build one AccountController in the test, and pass the same one to given().standaloneSetup(controller) for every request. Extract the Location with extract().header("Location").

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void openAndReadBackAnAccount() {
    AccountController controller = new AccountController(new AccountService());

    String location = given().standaloneSetup(controller)
        .contentType(ContentType.JSON)
        .body("{\"iban\": \"NL20INGB0001234567\", \"owner\": \"Sanne Smit\", \"currency\": \"EUR\"}")
        .when().post("/api/v1/accounts")
        .then().statusCode(201).extract().header("Location");

    given().standaloneSetup(controller).when().get(location)
        .then().statusCode(200).body("owner", equalTo("Sanne Smit")).body("balance", equalTo("0.00"));
    given().standaloneSetup(controller).when().get("/api/v1/accounts")
        .then().body("$", hasSize(3));
}

Exercise 2: Check the Reason in the Status Line

Change anUnknownAccount to also check that the status line contains Account acc-9999 does not exist, so the test fails if the 404 comes from an unknown route instead.

Hint

statusLine(..) takes a matcher. Import org.hamcrest.Matchers.containsString.

Solution
1
2
3
4
5
6
7
@Test
void anUnknownAccount() {
    accounts().when().get("/api/v1/accounts/{id}", "acc-9999")
        .then()
            .statusCode(404)
            .statusLine(containsString("Account acc-9999 does not exist"));
}

Add import static org.hamcrest.Matchers.containsString; to the class. The status line was 404 Account acc-9999 does not exist; for /api/v1/nothing, the status was 404 too, with no such reason.

Summary

You built StandaloneMockMvcTest, which tests the accounts controller through Spring MVC with REST Assured’s syntax: reading, opening and refusing accounts, in about half a second, with no server and no Spring context.

  • RestAssuredMockMvc puts REST Assured’s syntax on top of Spring’s MockMvc, which calls the DispatcherServlet directly, with no socket.
  • standaloneSetup(..) takes a controller you build yourself, so constructor injection matters.
  • Import given from RestAssuredMockMvc; the ordinary one sends real HTTP.
  • Errors in standalone mode have empty bodies; the reason is only in the status line.
  • Standalone mode leaves out security, problem details and configuration, so test those elsewhere.

Here are the commands you used in this guide:

1
2
git clone https://github.com/javanibble/rest-assured-examples.git
mvn test -pl module-11 -Dtest=StandaloneMockMvcTest

What’s Next

Next: continue with Test Spring Security Rules in a Web Slice With RestAssuredMockMvc, which tests the same controller with its real Spring MVC and Spring Security configuration, still with no server.

The code:

Go deeper:

Related guides:

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