Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a REST Assured test against a Spring Boot app started with webEnvironment = RANDOM_PORT that posts a JSON order and checks status 201, a Location header and the id in the body.

We start the application with @SpringBootTest(webEnvironment = RANDOM_PORT), inject the port with @LocalServerPort and pass it to REST Assured with given().port(port). Then given().contentType(ContentType.JSON) with the order JSON as the body, .when().post("/orders").then().statusCode(201).header("Location", containsString("/orders/")).body("id", notNullValue()) checks all three things. Because the request runs on a server thread, @Transactional rollback does not clean the data, so the test cleans up itself; for in-process tests, RestAssuredMockMvc gives the same style over MockMvc.

Why this question is asked

REST Assured is a Java library for testing HTTP APIs with a readable given, when, then style. It sends real HTTP requests, so a test written with it checks the API the way a client sees it: status codes, headers, JSON bodies, and everything in between such as filters, serialisation and security. Interviewers ask for this exercise because a correct answer touches several Spring testing details that people often get wrong, such as the port, the Location header and data cleanup. In this answer, we will look at the endpoint under test, write the test line by line, read the JSON with GPath, and then deal with the two practical points: why rollback does not work here, and when to use the MockMvc module instead.

1The Endpoint Under Test

The controller accepts a new order as JSON, saves it, and answers 201 Created with a Location header pointing at the new resource and the created order in the body. 201 with a Location header is the standard HTTP way to say 'I created something, and here is where it lives'.

Java
record NewOrder(@NotBlank String sku, @Positive int qty) {}
record OrderView(long id, String sku, int qty, String status) {}
@RestController
@RequestMapping("/orders")
class OrderController {
private final OrderService service;
OrderController(OrderService service) { this.service = service; }
@PostMapping
ResponseEntity<OrderView> create(@Valid @RequestBody NewOrder req, UriComponentsBuilder uri) {
OrderView created = service.place(req);
URI location = uri.path("/orders/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(created); // 201, Location: http://localhost:PORT/orders/17
}
}

Spring injects a UriComponentsBuilder that already knows the scheme, host and port of the current request, so the Location header is an absolute URL such as http://localhost:53817/orders/17. That detail matters for the assertion: we check that the header contains /orders/, not that it equals a fixed string.

2Starting the Application on a Random Port

RANDOM_PORT starts the real embedded server on a free port, and @LocalServerPort injects the port number into the test. A random port means two test classes or two builds on the same machine never fight over port 8080.

Java
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderApiTest {
@LocalServerPort int port;
@Autowired JdbcTemplate jdbc;
}

Many examples set RestAssured.port = port in a @BeforeEach method. That works, but RestAssured.port is a static, global setting, so test classes running in parallel against different servers can overwrite each other's value. Passing the port in each request with given().port(port), or building a shared RequestSpecification per class, avoids that.

3Writing the Test

Now the test itself. given() describes the request, when() sends it, and then() describes what we expect from the response.

Java
@Test
void createsOrder() {
given()
.port(port)
.contentType(ContentType.JSON)
.body("{\"sku\":\"A1\",\"qty\":2}")
.when()
.post("/orders")
.then()
.statusCode(201) // created
.header("Location", containsString("/orders/")) // http://localhost:53817/orders/17
.body("id", notNullValue()) // 17
.body("sku", equalTo("A1"))
.body("qty", equalTo(2))
.body("status", equalTo("OPEN"));
}
Step throughWhat the REST Assured test covers
Test (REST Assured)Embedded TomcatOrderControllerDatabase
POST /orders, JSON body, real HTTP
filters, security, JSON to NewOrder, validation
INSERT order, committed
201, Location, OrderView
HTTP response over the socket
check status, Location header and id

6 messages in order. Play them, or step through them one at a time.

Everything between the socket and the database runs as in production.

Each line in then() is an independent check. statusCode(201) fails with a clear message such as 'Expected status code <201> but was <400>' if validation rejected the body. header() takes the header name and a Hamcrest matcher, and containsString() passes for any absolute URL with the right path. body("id", notNullValue()) reads the id field from the JSON response and checks that it exists.

When a check fails, adding .log().ifValidationFails() after then() prints the full request and response, which is usually the fastest way to see what went wrong. We can also check that the id in the body and the id at the end of the Location header are the same, by extracting both.

4Reading JSON With GPath and Extracting Values

The strings passed to body() are GPath expressions, a path language borrowed from Groovy. A plain name such as id reads a top-level field, dots go deeper, square brackets index into arrays, and Groovy methods like size() work too. The matchers are standard Hamcrest matchers.

Java
// For a response like {"id":17,"lines":[{"sku":"A1","qty":2}],"customer":{"tier":"GOLD"}}
.body("lines.size()", is(1))
.body("lines[0].sku", equalTo("A1"))
.body("customer.tier", equalTo("GOLD"))
.body("lines.sku", hasItem("A1")) // collects sku from every line
// Extract values to use in the next step
ExtractableResponse<Response> r = given().port(port).contentType(ContentType.JSON)
.body("{\"sku\":\"A1\",\"qty\":2}").when().post("/orders").then().statusCode(201).extract();
int id = r.path("id"); // 17
assertThat(r.header("Location")).endsWith("/orders/" + id); // same id in both places
given().port(port).when().get(r.header("Location")).then().statusCode(200).body("id", equalTo(id));

Following the Location header with a GET is a nice final check: it proves the header points at a resource that really exists, not only that it has the right shape.

5Why Rollback Does Not Clean Up, and What to Do Instead

It is tempting to add @Transactional to the test class so the created orders disappear. That does not work here. The test-managed transaction is bound to the test thread, but the request is handled on one of Tomcat's worker threads, which runs its own transaction and commits it. The test's rollback has nothing to undo, and orders accumulate between tests.

So a real HTTP test cleans up explicitly. If tests run one at a time, truncating the order tables in an @AfterEach method is simplest. If they run in parallel, each test should use its own data, such as a unique customer id, and delete or filter only that. Assertions such as 'there is exactly one order' should be scoped to the test's own data for the same reason.

Java
@AfterEach
void cleanUp() {
jdbc.execute("TRUNCATE TABLE orders RESTART IDENTITY CASCADE"); // PostgreSQL; fine for sequential tests
}

6The Same Style Without a Server: RestAssuredMockMvc

Sometimes we want REST Assured's readable style without starting Tomcat, for example for many controller tests that do not need real HTTP. The spring-mock-mvc module of REST Assured provides RestAssuredMockMvc, which runs the same given, when, then chain against MockMvc in the same thread.

Java
@SpringBootTest
@AutoConfigureMockMvc
class OrderMvcStyleTest {
@Autowired MockMvc mvc;
@Test
void createsOrder() {
RestAssuredMockMvc.given().mockMvc(mvc)
.contentType(ContentType.JSON).body("{\"sku\":\"A1\",\"qty\":2}")
.when().post("/orders")
.then().statusCode(201).body("id", notNullValue()); // no server, no socket
}
}

Because MockMvc calls the DispatcherServlet on the test thread, a test like this can use @Transactional rollback. The trade-off is that it skips the servlet container, so it does not test real HTTP behaviour such as container-level filters, compression or the actual network stack.

7Follow-up questions

Why use REST Assured instead of TestRestTemplate?

Both send real HTTP. REST Assured's strength is the fluent checks on status, headers and JSON paths in one chain, with helpful failure messages and request logging. TestRestTemplate returns a ResponseEntity that we then assert on with AssertJ, which is fine but more verbose for JSON checks. Many teams use REST Assured for API-focused suites and TestRestTemplate or RestTestClient elsewhere.

How do you test the validation error case?

Send an invalid body, such as qty 0, and expect statusCode(400). If the application returns RFC 9457 problem details, which Spring supports through ProblemDetail, check the fields too, for example body("status", equalTo(400)) and a check on the detail or the field errors that your error handler produces.

How do you add authentication to the requests?

Add the header in given(), for example given().header("Authorization", "Bearer " + token) or REST Assured's auth().oauth2(token). The token can come from a test helper that signs a JWT with a test key the application trusts in the test profile, so the security filter chain is exercised for real.

8Conclusion

In this answer, we wrote a REST Assured test against a Spring Boot application started on a random port. @LocalServerPort supplies the port, passed per request with given().port(port) so parallel classes do not clash. The test posts JSON, then checks statusCode(201), a Location header containing /orders/ and a non-null id, using Hamcrest matchers and GPath paths, and can extract values to follow the Location header. Because the request runs on a server thread, @Transactional rollback does not clean up, so the test removes its data explicitly, and RestAssuredMockMvc offers the same style in-process when a real server is not needed.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd annotate the class with SpringBootTest webEnvironment RANDOM_PORT so the real embedded server starts on a free port, and inject the port with @LocalServerPort. I pass it with given().port(port) rather than setting RestAssured.port, because that's a static global and parallel test classes can overwrite it.

Then, if they want more

The test is given, port, contentType ContentType.JSON, body with sku A1 and qty 2, when post /orders, then statusCode 201, header Location with containsString /orders/, and body id notNullValue. The body checks use GPath, so I can also check nested fields like lines[0].sku, and the matchers are Hamcrest. I'd add log ifValidationFails so a failure prints the request and response.

For a stronger test I extract the response, check the id at the end of the Location header matches the id in the body, and then do a GET on the Location to prove the resource exists. Containing /orders/ rather than an exact URL matters, because the header is absolute and includes the random port.

One important detail: @Transactional on this test doesn't roll anything back, because the request is handled on a Tomcat worker thread that commits its own transaction. So I clean up explicitly, by truncating in AfterEach for sequential tests, or with unique data per test when running in parallel.

If I don't need a real server, RestAssuredMockMvc gives the same style over MockMvc.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a REST Assured test against a Spring Boot app started with webEnvironment =...": https://scrivio-interview-library.netlify.app/java/integration-testing/345e0857ce/