@SpringBootTest for full flows
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every unit and slice test of ShopLite can pass while the app still fails to start, because a bean is missing or security blocks a URL. What proves the whole app works together?
@SpringBootTest with webEnvironment RANDOM_PORT
@SpringBootTest is a Spring Boot test annotation that starts the whole application, as main would: every bean, security, transactions and the database. A test then drives it from the outside.
Start the whole ShopLite application on a random port. This class is a smoke test: it proves that every bean is wired and the server answers.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)class ShopliteApiSmokeIT {
@LocalServerPort private int port; // for example 54817, different on every run}The webEnvironment attribute decides the web side: MOCK (the default: no server, use MockMvc), RANDOM_PORT (a real Tomcat on a free port), DEFINED_PORT (the configured port, usually 8080) or NONE (no web layer at all).
RANDOM_PORT avoids clashes with an app already running on 8080 and tests the real HTTP path: Tomcat, filters, headers. @LocalServerPort gives the chosen port, as in ShopLite's ShopliteApiSmokeIT.
ShopLite's full tests add @ActiveProfiles("test") for the MySQL test database and @Sql to load the seed rows, and are named *IT so Failsafe runs them in mvn verify.
Predict the output
Pick the webEnvironment
Choose the setting that fits each test.
Round 1 of 3
Which webEnvironment fits?
Calling the API: RestTestClient or MockMvc with @AutoConfigureMockMvc
RestTestClient is Spring Framework 7's test client for real HTTP calls. You write client.get().uri(...), then check the answer with expectStatus(), expectHeader() and expectBody().jsonPath(...).
Call the running app with RestTestClient and check the answer. The test never builds a URL with the port: Boot points the client at the random port.
Example 1 · src/test/java/com/shoplite/CatalogueReadIT.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
package com.shoplite;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.jdbc.Sql;import org.springframework.test.web.servlet.client.RestTestClient;
/** The whole app on a random port, called over real HTTP with RestTestClient. */@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)@AutoConfigureRestTestClient@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_CLASS)class CatalogueReadIT {
@Autowired private RestTestClient client; // already pointed at http://localhost:<random port>
@Test void readsASeedProductOverHttp() { client.get().uri("/api/v1/products/1") .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.sku").isEqualTo("MOB-RN13") .jsonPath("$.categoryName").isEqualTo("Mobiles"); }
@Test void aMissingProductIsAProblem() { client.get().uri("/api/v1/products/999") .exchange() .expectStatus().isNotFound() .expectHeader().contentType(MediaType.APPLICATION_PROBLEM_JSON) .expectBody() .jsonPath("$.detail").isEqualTo("Product 999 was not found."); }}$ ./mvnw verify -Dit.test=CatalogueReadIT -Dtest=none -Dsurefire.failIfNoSpecifiedTests=false ... INFO o.s.boot.tomcat.TomcatWebServer : Tomcat started on port 54817 (http) with context path '/' INFO com.shoplite.CatalogueReadIT : Started CatalogueReadIT in 7.384 seconds (process running for 8.62) [INFO] Running com.shoplite.CatalogueReadIT [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 8.913 s -- in com.shoplite.CatalogueReadIT
What this code does
@AutoConfigureRestTestClientgives aRestTestClientbound to the random port; the test never builds a URL with the port itself.exchange()sends the request;expectStatus(),expectHeader()andexpectBody().jsonPath(...)check the answer, like MockMvc's matchers.- The log shows the real price: a full context with Tomcat, Hibernate and Flyway took about 7 seconds to start.
@AutoConfigureRestTestClient on a RANDOM_PORT test makes Boot create the client. The other way is @AutoConfigureMockMvc on a MOCK test: the full context, but requests go through MockMvc in memory. ShopLite's OrderOwnershipIT and AccessMatrixIT do this, and use jwt() to act as a signed-in user without a real token.
One difference matters. With MockMvc the request runs in the test's own thread, so @Transactional on the test rolls everything back. With RANDOM_PORT the request runs in a Tomcat thread, outside the test's transaction, so its changes are committed and the test must reset the data itself.
Find the bug
Find the mistake
Click the line that causes the problem.
The next run of this test fails with 409 already-exists. Which line is the cause?
Round 1 of 2TestRestTemplate for this; it still exists in Boot 4 (org.springframework.boot.resttestclient.TestRestTemplate), but new tests use RestTestClient.A full flow: create a product, place an order, read it back
A flow test follows one real user journey through several endpoints, in order, and checks the result a user would see. It is a full-context test, so a handful is enough.
Follow one journey in order: sign in, create a product, order it, read the order back. Example 2 shows the idea in plain Java; Example 3 is the Spring test.
Example 2 · A full flow over real HTTP, in plain Java
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;
import java.io.IOException;import java.io.OutputStream;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;
/** A very small ShopLite: products and orders in maps, served over real HTTP. */class MiniShop { record Product(int id, String name, BigDecimal price, int stock) { }
record Order(int id, int productId, int quantity, BigDecimal total) { }
private final Map<Integer, Product> products = new HashMap<>(); private final Map<Integer, Order> orders = new HashMap<>(); private int nextProductId = 16; private int nextOrderId = 17;
synchronized void handle(HttpExchange exchange) throws IOException { String method = exchange.getRequestMethod(); String path = exchange.getRequestURI().getPath(); String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); String host = "http://" + exchange.getRequestHeaders().getFirst("Host");
if (method.equals("POST") && path.equals("/api/v1/products")) { Product p = new Product(nextProductId++, text(body, "name"), new BigDecimal(number(body, "price")), Integer.parseInt(number(body, "stock"))); products.put(p.id(), p); exchange.getResponseHeaders().add("Location", host + path + "/" + p.id()); send(exchange, 201, json(p)); } else if (method.equals("GET") && path.startsWith("/api/v1/products/")) { Product p = products.get(idAtEnd(path)); send(exchange, p == null ? 404 : 200, p == null ? "{\"title\":\"Resource not found\"}" : json(p)); } else if (method.equals("POST") && path.equals("/api/v1/orders")) { int productId = Integer.parseInt(number(body, "productId")); int quantity = Integer.parseInt(number(body, "quantity")); Product p = products.get(productId); if (p.stock() < quantity) { send(exchange, 409, "{\"title\":\"Not enough stock\"}"); return; } products.put(p.id(), new Product(p.id(), p.name(), p.price(), p.stock() - quantity)); Order o = new Order(nextOrderId++, productId, quantity, p.price().multiply(BigDecimal.valueOf(quantity))); orders.put(o.id(), o); exchange.getResponseHeaders().add("Location", host + path + "/" + o.id()); send(exchange, 201, json(o)); } else if (method.equals("GET") && path.startsWith("/api/v1/orders/")) { Order o = orders.get(idAtEnd(path)); send(exchange, o == null ? 404 : 200, o == null ? "{\"title\":\"Resource not found\"}" : json(o)); } else { send(exchange, 404, "{\"title\":\"Resource not found\"}"); } }
private static String json(Product p) { return "{\"id\":" + p.id() + ",\"name\":\"" + p.name() + "\",\"price\":" + p.price() + ",\"stock\":" + p.stock() + "}"; }
private static String json(Order o) { return "{\"id\":" + o.id() + ",\"status\":\"PLACED\",\"productId\":" + o.productId() + ",\"quantity\":" + o.quantity() + ",\"total\":" + o.total() + "}"; }
private static int idAtEnd(String path) { return Integer.parseInt(path.substring(path.lastIndexOf('/') + 1)); }
private static String text(String json, String field) { Matcher m = Pattern.compile("\"" + field + "\"\\s*:\\s*\"([^\"]*)\"").matcher(json); return m.find() ? m.group(1) : ""; }
private static String number(String json, String field) { Matcher m = Pattern.compile("\"" + field + "\"\\s*:\\s*([0-9.]+)").matcher(json); return m.find() ? m.group(1) : "0"; }
private static void send(HttpExchange exchange, int status, String json) throws IOException { byte[] bytes = json.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.sendResponseHeaders(status, bytes.length); try (OutputStream out = exchange.getResponseBody()) { out.write(bytes); } }}
public class ShopFlowDemo { static HttpClient client = HttpClient.newHttpClient(); static String base;
static HttpResponse<String> call(String method, String path, String json) throws Exception { HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path)); if (json == null) { request.method(method, HttpRequest.BodyPublishers.noBody()); } else { request.header("Content-Type", "application/json").method(method, HttpRequest.BodyPublishers.ofString(json)); } HttpResponse<String> response = client.send(request.build(), HttpResponse.BodyHandlers.ofString()); String location = response.headers().firstValue("Location").map(l -> " Location " + URI.create(l).getPath()).orElse(""); System.out.println(method + " " + path + " -> " + response.statusCode() + location); System.out.println(" " + response.body()); return response; }
static void expect(String what, boolean ok) { System.out.println((ok ? "PASS " : "FAIL ") + what); }
public static void main(String[] args) throws Exception { MiniShop shop = new MiniShop(); HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); // a random free port server.createContext("/", shop::handle); server.start(); base = "http://localhost:" + server.getAddress().getPort(); try { HttpResponse<String> created = call("POST", "/api/v1/products", "{\"name\": \"Zebronics Wireless Keyboard\", \"price\": 999.00, \"stock\": 30}"); HttpResponse<String> placed = call("POST", "/api/v1/orders", "{\"productId\": 16, \"quantity\": 2}"); HttpResponse<String> order = call("GET", "/api/v1/orders/17", null); HttpResponse<String> product = call("GET", "/api/v1/products/16", null);
expect("product created (201)", created.statusCode() == 201); expect("order placed (201)", placed.statusCode() == 201); expect("order total is 1998.00", order.body().contains("\"total\":1998.00")); expect("stock went from 30 to 28", product.body().contains("\"stock\":28")); } finally { server.stop(0); } }}POST /api/v1/products -> 201 Location /api/v1/products/16
{"id":16,"name":"Zebronics Wireless Keyboard","price":999.00,"stock":30}
POST /api/v1/orders -> 201 Location /api/v1/orders/17
{"id":17,"status":"PLACED","productId":16,"quantity":2,"total":1998.00}
GET /api/v1/orders/17 -> 200
{"id":17,"status":"PLACED","productId":16,"quantity":2,"total":1998.00}
GET /api/v1/products/16 -> 200
{"id":16,"name":"Zebronics Wireless Keyboard","price":999.00,"stock":28}
PASS product created (201)
PASS order placed (201)
PASS order total is 1998.00
PASS stock went from 30 to 28What this code does
- A tiny shop on
com.sun.net.httpserver, started on port 0 (any free port), plays the app;HttpClientplays the test client. - The flow creates product 16, orders 2 of it as order 17, then reads both back: the same steps as the Spring test in Example 3.
- The program prints only the path of each
Location, never the port, so the output is the same on every run.
Example 3 · src/test/java/com/shoplite/OrderFlowIT.java
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
package com.shoplite;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.jdbc.Sql;import org.springframework.test.web.servlet.client.RestTestClient;
import com.shoplite.auth.TokenResponse;
/** * One business flow end to end: the admin creates a product, places an order for customer 1, * and reads both back. Real Tomcat, real security, real MySQL. Nothing is rolled back, * so the reset script gives the same ids (product 16, order 17) on every run. */@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)@AutoConfigureRestTestClient@ActiveProfiles("test")@Sql(scripts = "/reset-test-db.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)class OrderFlowIT {
@Autowired private RestTestClient client;
private String adminToken;
@BeforeEach void logInAsAdmin() { TokenResponse tokens = client.post().uri("/api/v1/auth/login") .contentType(MediaType.APPLICATION_JSON) .body(""" {"email": "admin@shoplite.example", "password": "shoplite-admin-dev"} """) .exchange() .expectStatus().isOk() .expectBody(TokenResponse.class) .returnResult().getResponseBody(); adminToken = "Bearer " + tokens.accessToken(); }
@Test void createProductPlaceOrderAndReadItBack() { client.post().uri("/api/v1/products") .header("Authorization", adminToken) .contentType(MediaType.APPLICATION_JSON) .body(""" {"sku": "ACC-KB100", "name": "Zebronics Wireless Keyboard", "categoryId": 4, "price": 999.00, "stock": 30} """) .exchange() .expectStatus().isCreated() .expectHeader().value("Location", location -> assertThat(location).endsWith("/api/v1/products/16"));
client.post().uri("/api/v1/orders") .header("Authorization", adminToken) .contentType(MediaType.APPLICATION_JSON) .body(""" {"customerId": 1, "addressId": 1, "items": [{"productId": 16, "quantity": 2}]} """) .exchange() .expectStatus().isCreated() .expectBody().jsonPath("$.id").isEqualTo(17);
client.get().uri("/api/v1/orders/17") .header("Authorization", adminToken) .exchange() .expectStatus().isOk() .expectBody() .jsonPath("$.status").isEqualTo("PLACED") .jsonPath("$.items[0].sku").isEqualTo("ACC-KB100") .jsonPath("$.items[0].unitPrice").isEqualTo(999.00) .jsonPath("$.total").isEqualTo(1998.00);
client.get().uri("/api/v1/products/16") // public: no token needed .exchange() .expectStatus().isOk() .expectBody().jsonPath("$.stock").isEqualTo(28); }}[INFO] Running com.shoplite.OrderFlowIT INFO com.shoplite.product.ProductService : Created product 16 (ACC-KB100) [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.866 s -- in com.shoplite.OrderFlowIT
What this code does
@BeforeEachsigns in through the real login endpoint and keeps"Bearer " + accessTokenfor the admin-only calls.- Product 16 and order 17 are fixed because
@Sqlrunsreset-test-db.sqlbefore the method, and TRUNCATE restarts the AUTO_INCREMENT counters. - The last call proves a side effect a user can see: stock 30 minus 2 is 28. A unit test with mocks could not show that the pieces really work together.
Each step depends on the one before, so one test method holds the whole flow. The reset script runs before the test method, so the ids are the same on every run: the new product is 16 and the new order 17.
The flow signs in through the real POST /api/v1/auth/login, so it also proves that login, the JWT and the URL rules work together.
Order of execution
Order the flow
Put the steps of the ShopLite order flow in the order the test runs them.
Context caching and keeping the full-test count small
The context cache keeps every test context Spring has started, keyed by the test configuration. A later test class with the same key reuses the context and starts in milliseconds.
Count how often Spring starts a context. Example 4 shows the cache log; Example 5 counts the starts for four test classes.
Example 4 · Seeing the context cache at work
Runs in: a terminal in the shoplite-api project (Maven, MySQL test database)
# src/test/resources/application-test.properties (add while you look at the cache)logging.level.org.springframework.test.context.cache=DEBUGDEBUG o.s.t.c.cache.DefaultCacheAwareContextLoaderDelegate : Storing ApplicationContext [1268843170] in cache under key [MergedContextConfiguration@1d9b7cce testClass = com.shoplite.order.OrderOwnershipIT, ...] DEBUG org.springframework.test.context.cache : Spring test ApplicationContext cache statistics: [DefaultContextCache@6b2e46af size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1, failureCount = 0] ... DEBUG o.s.t.c.cache.DefaultCacheAwareContextLoaderDelegate : Retrieved ApplicationContext [1268843170] from cache with key [MergedContextConfiguration@4d7a4b1e testClass = com.shoplite.AccessMatrixIT, ...] DEBUG org.springframework.test.context.cache : Spring test ApplicationContext cache statistics: [DefaultContextCache@6b2e46af size = 4, maxSize = 32, parentContextCount = 0, hitCount = 61, missCount = 4, failureCount = 0]
What this code does
missCountis how many contexts were started,hitCounthow many times one was reused. Here 4 contexts served 65 test-class lookups.- The key printed in the log is the merged configuration: two classes with the same annotations get the same key.
- If
missCountgrows with every new IT class, look for per-class@MockitoBeanfields, extra profiles or@DirtiesContext.
Example 5 · Counting context starts
import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;
/** Spring keys a cached test context by its configuration; same key = same context, no new start. */public class ContextCacheDemo { record TestClass(String name, String config) { }
static void runSuite(String title, TestClass[] classes) { Map<String, Integer> cache = new HashMap<>(); int hits = 0; int misses = 0; System.out.println(title); for (TestClass test : classes) { if (cache.containsKey(test.config())) { hits++; System.out.println(" " + test.name() + ": reuses context " + cache.get(test.config())); } else { misses++; cache.put(test.config(), cache.size() + 1); System.out.println(" " + test.name() + ": starts context " + cache.size() + " (about 6 s)"); } } System.out.println(" contexts started = " + misses + ", reused = " + hits + ", startup time about " + (misses * 6) + " s"); }
public static void main(String[] args) { String full = "@SpringBootTest + @AutoConfigureMockMvc + profile test"; runSuite("Same configuration everywhere:", new TestClass[] { new TestClass("OrderOwnershipIT", full), new TestClass("AccessMatrixIT", full), new TestClass("SignUpAndSignInIT", full), new TestClass("CategoryFlowIT", full)});
runSuite("One class adds a @MockitoBean, one uses another profile:", new TestClass[] { new TestClass("OrderOwnershipIT", full), new TestClass("AccessMatrixIT", full + " + @MockitoBean EmailSender"), new TestClass("SignUpAndSignInIT", "@SpringBootTest + @AutoConfigureMockMvc + profile dev"), new TestClass("CategoryFlowIT", full)}); }}Same configuration everywhere: OrderOwnershipIT: starts context 1 (about 6 s) AccessMatrixIT: reuses context 1 SignUpAndSignInIT: reuses context 1 CategoryFlowIT: reuses context 1 contexts started = 1, reused = 3, startup time about 6 s One class adds a @MockitoBean, one uses another profile: OrderOwnershipIT: starts context 1 (about 6 s) AccessMatrixIT: starts context 2 (about 6 s) SignUpAndSignInIT: starts context 3 (about 6 s) CategoryFlowIT: reuses context 1 contexts started = 3, reused = 1, startup time about 18 s
What this code does
- Four test classes with the same configuration start one context and reuse it three times.
- Adding one
@MockitoBean(here a made-upEmailSender) or another profile changes the key, so the same four classes start three contexts. - The 6 seconds per start is an example figure; measure your own with the cache log in Example 4.
The key is built from the classes, profiles, properties, webEnvironment and the set of @MockitoBean fields. Every difference creates a new context: one class with an extra @MockitoBean, another profile or a @TestPropertySource. @DirtiesContext throws a context away on purpose. Each new context costs seconds and keeps its own connection pool open.
So keep full tests few and alike: the same annotations, no per-class mocks, a shared base setup. Test rules with unit tests, HTTP shapes with @WebMvcTest, queries with @DataJpaTest, and leave @SpringBootTest for wiring and a handful of key flows.
Next step
Check your understanding
11 quick questions