Testing Spring Boot applications
A Spring Boot test can run your code with no Spring at all, with the full application context, or with only one layer of it. Each choice trades speed for realism. This page explains how the Spring test framework builds and caches contexts, then runs every common kind of test against a small order API, including what the output looks like when a test fails.
Contents
How Spring Boot tests work
Most of the code in a Spring application is plain Java: services, mappers and validators that take their collaborators through the constructor. Those classes can be tested like any other Java class, with JUnit and Mockito and no Spring at all. Spring only needs to be part of a test when the thing being tested is Spring's own work: request mapping, JSON conversion, validation, transactions, security rules or the way beans are wired together.
For those tests, the Spring TestContext framework, in the spring-test@Autowired@SpringBootTestSpringApplication.run@SpringBootApplicationapplication.properties
Starting a context takes from a fraction of a second to many seconds, so the framework keeps every context it starts in a cache, keyed by the test's configuration. A second test class with the same configuration gets the same context back without starting it again. This cache is why a large test suite can run hundreds of @SpringBootTest@MockitoBean
| Test | What it starts | Relative speed | Best for |
|---|---|---|---|
| Plain unit test | Nothing; you call new | Fastest | Business logic in services and other plain classes |
Slice test (@WebMvcTest@DataJpaTest@JsonTest | One layer of the application | Fast | Controllers, repositories or JSON mapping on their own |
@SpringBootTest | The whole context, no server | Slower | Requests through every layer, with MockMvc |
@SpringBootTest(webEnvironment = RANDOM_PORT) | The whole context and a real server | Slowest | Real HTTP behaviour: filters, error pages, the servlet container |
The programs below use Spring Boot 4.1 with JUnit 6. Each one contains the application code and the test class together, and its mainsrc/test/java
Unit tests without Spring
An order service that looks up a price and saves the order is typical service code: the logic is in the class, and the collaborators are interfaces that are easy to replace. The test creates the service with new
package demo.testing.unit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
public class PlainUnitTest {
record Order(long id, String sku, int quantity, BigDecimal total) {
}
interface PriceClient {
Optional<BigDecimal> unitPrice(String sku);
}
interface OrderRepository {
Order save(Order order);
}
// the class under test: plain Java, so it can be tested without Spring
static class OrderService {
private final PriceClient prices;
private final OrderRepository orders;
OrderService(PriceClient prices, OrderRepository orders) {
this.prices = prices;
this.orders = orders;
}
Order place(long id, String sku, int quantity) {
BigDecimal unit = prices.unitPrice(sku)
.orElseThrow(() -> new IllegalArgumentException("unknown sku " + sku));
return orders.save(new Order(id, sku, quantity,
unit.multiply(BigDecimal.valueOf(quantity))));
}
}
static class OrderServiceTest {
PriceClient prices = mock(PriceClient.class);
OrderRepository orders = mock(OrderRepository.class);
OrderService service = new OrderService(prices, orders);
@Test
void totalIsUnitPriceTimesQuantity() {
when(prices.unitPrice("book")).thenReturn(Optional.of(new BigDecimal("12.50")));
when(orders.save(any())).thenAnswer(call -> call.getArgument(0));
Order order = service.place(1, "book", 3);
assertThat(order.total()).isEqualByComparingTo("37.50");
verify(orders).save(order);
}
@Test
void unknownSkuIsRejectedAndNothingIsSaved() {
when(prices.unitPrice("ghost")).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.place(2, "ghost", 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("unknown sku ghost");
verify(orders, never()).save(any());
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(OrderServiceTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
}
});
}
}
totalIsUnitPriceTimesQuantity(): SUCCESSFUL
unknownSkuIsRejectedAndNothingIsSaved(): SUCCESSFUL
- Both tests passed with no application context, no auto-configuration and no Spring annotation in the test.
- The first test checks the arithmetic: 3 × 12.50 is 37.50. It uses
becauseisEqualByComparingTo also compares the scale, soBigDecimal.equals and37.50 would not be equal.37.5 - The second test checks both the exception and its absence of side effects:
fails if the service saved something before throwing.verify(orders, never()).save(any())
Constructor injection is what makes this possible. A class whose dependencies arrive through @Autowired-javaagent:mockito-core.jar
@SpringBootTest with MockMvcTester
A controller test needs Spring, because the request mapping, the JSON conversion and the status codes are all done by Spring MVC. This program sends three requests to an order controller: one that finds an order, one for a missing order, and one that creates an order:
package demo.testing.mockmvc;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.test.web.servlet.assertj.MvcTestResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.server.ResponseStatusException;
public class MockMvcTest {
record Order(long id, String sku, int quantity) {
}
record NewOrder(String sku, int quantity) {
}
@SpringBootApplication
static class ShopApplication {
}
@RestController
@RequestMapping("/orders")
static class OrderController {
private final Map<Long, Order> orders = new ConcurrentHashMap<>(
Map.of(1L, new Order(1, "book", 2)));
private final AtomicLong nextId = new AtomicLong(2);
@GetMapping("/{id}")
Order get(@PathVariable long id) {
Order order = orders.get(id);
if (order == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no order " + id);
}
return order;
}
@PostMapping
ResponseEntity<Order> create(@RequestBody NewOrder request) {
Order order = new Order(nextId.getAndIncrement(), request.sku(), request.quantity());
orders.put(order.id(), order);
return ResponseEntity.created(URI.create("/orders/" + order.id())).body(order);
}
}
@SpringBootTest(properties = {"spring.main.banner-mode=off", "logging.level.root=WARN"})
static class OrderControllerTest {
@Autowired
WebApplicationContext context;
MockMvcTester mvc;
@BeforeEach
void setUp() {
mvc = MockMvcTester.from(context);
}
@Test
void returnsAnExistingOrder() throws Exception {
MvcTestResult result = mvc.get().uri("/orders/1").exchange();
print("GET /orders/1", result);
assertThat(result).hasStatusOk()
.bodyJson().extractingPath("$.sku").isEqualTo("book");
}
@Test
void returns404ForAMissingOrder() throws Exception {
MvcTestResult result = mvc.get().uri("/orders/99").exchange();
print("GET /orders/99", result);
assertThat(result).hasStatus(HttpStatus.NOT_FOUND);
}
@Test
void createsAnOrder() throws Exception {
MvcTestResult result = mvc.post().uri("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"sku": "pen", "quantity": 5}""")
.exchange();
print("POST /orders", result);
assertThat(result).hasStatus(HttpStatus.CREATED)
.hasHeader("Location", "/orders/2")
.bodyJson().isLenientlyEqualTo("""
{"sku": "pen", "quantity": 5}""");
}
static void print(String request, MvcTestResult result) throws Exception {
var response = result.getResponse();
System.out.println(" " + request + " -> " + response.getStatus() + " "
+ response.getContentAsString().replace("\n", ""));
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(OrderControllerTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
}
});
}
}
WARN o.s.b.j.a.JpaBaseConfiguration$JpaWebConfiguration - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
GET /orders/99 -> 404
returns404ForAMissingOrder(): SUCCESSFUL
POST /orders -> 201 {"id":2,"sku":"pen","quantity":5}
createsAnOrder(): SUCCESSFUL
GET /orders/1 -> 200 {"id":1,"sku":"book","quantity":2}
returnsAnExistingOrder(): SUCCESSFUL
found@SpringBootTest on its own: it searched the test's package for aShopApplication . No server started; the default web environment,@SpringBootConfiguration , gives a web application context with a mock servlet environment.MOCK returned 200 with the order as JSON, written by Jackson.GET /orders/1 took one field out with a JSON path.extractingPath("$.sku") returned 201, aPOST /orders header ofLocation and the new order./orders/2 compared only the fields in the expected JSON, so the generatedisLenientlyEqualTo did not have to be listed.id returned 404 with an empty body. In a running application the same request returns a JSON error body, as the real-server test below shows. MockMvc calls theGET /orders/99 directly, so the servlet container's forward to Spring Boot'sDispatcherServlet page never happens./error- The tests ran in the order 404, create, get. JUnit's default method order is deterministic but deliberately not obvious, so tests must not depend on each other. Here the create test happened to run before the get test, and both still passed because they touch different orders.
MockMvcTesterMockMvcMockMvcTester.from(context)@AutoConfigureMockMvcMockMvcTesterspring-boot-webmvc-test
The WARN@DataJpaTestspring.jpa.open-in-viewfalse
Replacing a bean with @MockitoBean
Some beans cannot run in a test: a client for a payment provider, a mail sender, anything that needs the network. Here the real PriceClient
package demo.testing.mockitobean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import java.math.BigDecimal;
import java.util.Optional;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Service;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
public class MockitoBeanTest {
@SpringBootApplication
static class ShopApplication {
}
// the real bean would call a remote pricing service
@Service
static class PriceClient {
Optional<BigDecimal> unitPrice(String sku) {
throw new IllegalStateException("no network in tests");
}
}
@RestController
static class PriceController {
private final PriceClient prices;
PriceController(PriceClient prices) {
this.prices = prices;
}
@GetMapping("/prices/{sku}")
String price(@PathVariable String sku) {
return prices.unitPrice(sku).map(p -> sku + " costs " + p).orElse("unknown " + sku);
}
}
@SpringBootTest(properties = "spring.main.banner-mode=off")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
static class PriceControllerTest {
@MockitoBean
PriceClient prices;
@Autowired
PriceController controller;
@Autowired
WebApplicationContext context;
@Test
@Order(1)
void usesTheStubbedPrice() {
System.out.println(" injected bean is a Mockito mock: "
+ Mockito.mockingDetails(prices).isMock());
given(prices.unitPrice("book")).willReturn(Optional.of(new BigDecimal("12.50")));
assertThat(MockMvcTester.from(context).get().uri("/prices/book"))
.hasStatusOk().hasBodyTextEqualTo("book costs 12.50");
then(prices).should().unitPrice("book");
}
@Test
@Order(2)
void stubsAreResetAfterEachTest() {
// no stubbing here: the stub from the first test has been removed
System.out.println(" unstubbed call returns: " + prices.unitPrice("book"));
assertThat(controller.price("book")).isEqualTo("unknown book");
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(PriceControllerTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
}
});
}
}
WARN o.s.b.j.a.JpaBaseConfiguration$JpaWebConfiguration - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
injected bean is a Mockito mock: true
usesTheStubbedPrice(): SUCCESSFUL
unstubbed call returns: Optional.empty
stubsAreResetAfterEachTest(): SUCCESSFUL
- The
injected into the test, and into the controller, was a Mockito mock. The real class'sPriceClient never ran, or the test would have failed with "no network in tests".unitPrice - The first test stubbed the price, sent a request through MockMvc and got
.book costs 12.50 checked that the controller really called the client.then(prices).should().unitPrice("book") - The second test made no stubbing, and the same mock returned
. Spring resetsOptional.empty mocks after each test method, so a stub cannot leak from one test into the next. Mockito returns an empty@MockitoBean , notOptional , for an unstubbed method that returnsnull .Optional
@MockitoBean@MockitoSpyBean@MockBean@SpyBean@Configuration
Each set of @MockitoBean
Testing over real HTTP
Some behaviour exists only in a running server: servlet filters registered with the container, compression, the error page, and the conversion of the HTTP response by a real client. RANDOM_PORT
package demo.testing.realserver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.client.RestTestClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
public class RealServerTest {
record Order(long id, String sku, int quantity) {
}
@SpringBootApplication
static class ShopApplication {
}
@RestController
static class OrderController {
@GetMapping("/orders/{id}")
Order get(@PathVariable long id) {
if (id != 1) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "no order " + id);
}
return new Order(1, "book", 2);
}
}
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,
properties = "spring.main.banner-mode=off")
static class OrderApiTest {
@LocalServerPort
int port;
RestTestClient client;
@BeforeEach
void setUp() {
client = RestTestClient.bindToServer().baseUrl("http://localhost:" + port).build();
}
@Test
void returnsJsonOverHttp() {
client.get().uri("/orders/1").exchange()
.expectStatus().isOk()
.expectHeader().contentType("application/json")
.expectBody(Order.class).isEqualTo(new Order(1, "book", 2));
}
@Test
void errorBodyComesFromTheRealErrorPage() {
String body = client.get().uri("/orders/99").exchange()
.expectStatus().isNotFound()
.expectBody(String.class).returnResult().getResponseBody();
// timestamp varies on every run, so print only the stable fields
System.out.println(" 404 body has status, error and path: "
+ (body.contains("\"status\":404") && body.contains("\"error\":\"Not Found\"")
&& body.contains("\"path\":\"/orders/99\"")));
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(OrderApiTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
}
});
// the cached test context keeps Tomcat running; a build tool's test JVM exits here
System.exit(0);
}
}
WARN o.s.b.j.a.JpaBaseConfiguration$JpaWebConfiguration - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
returnsJsonOverHttp(): SUCCESSFUL
404 body has status, error and path: true
errorBodyComesFromTheRealErrorPage(): SUCCESSFUL
injected the port Tomcat picked. A random port lets several test runs, or several test contexts, run on one machine without clashing.@LocalServerPort- The first test checked the status, the
header and the body, whichContent-Type converted back into anRestTestClient and compared withOrder .equals - The second test got the JSON error body that the MockMvc test did not: Tomcat forwarded the 404 to Spring Boot's error controller, which wrote
,status anderror . The body also has apath , so the program prints only whether the stable fields are there.timestamp
RestTestClientWebTestClientRestClientTestRestTemplate@AutoConfigureTestRestTemplate@AutoConfigureRestTestClientRestTestClientTestRestTemplateRestTestClient
The program ends with System.exit(0)@Transactional
Test slices: one layer at a time
A slice test starts only the part of the application that one layer needs. @JsonTest
package demo.testing.json;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.json.JsonContent;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RestController;
public class JsonSliceTest {
record Shipment(@JsonProperty("tracking_id") String trackingId, LocalDate shipped) {
}
@SpringBootApplication
static class ShopApplication {
}
@RestController
static class ShipmentController {
}
@JsonTest(properties = "spring.main.banner-mode=off")
static class ShipmentJsonTest {
@Autowired
JacksonTester<Shipment> json;
@Autowired
ApplicationContext context;
@Test
void writesSnakeCaseAndIsoDates() throws Exception {
JsonContent<Shipment> written = json.write(
new Shipment("TRK-7", LocalDate.of(2026, 3, 9)));
System.out.println(" written: " + written.getJson());
assertThat(written).extractingJsonPathStringValue("$.tracking_id").isEqualTo("TRK-7");
assertThat(written).extractingJsonPathStringValue("$.shipped")
.isEqualTo("2026-03-09");
}
@Test
void readsJsonBack() throws Exception {
Shipment read = json.parseObject("""
{"tracking_id": "TRK-8", "shipped": "2026-03-10"}""");
System.out.println(" read: " + read);
assertThat(read.shipped()).isEqualTo(LocalDate.of(2026, 3, 10));
}
@Test
void loadsOnlyTheJsonPartOfTheApplication() {
int controllers = context.getBeanNamesForType(ShipmentController.class).length;
System.out.println(" controllers in the context: " + controllers
+ ", beans in total: " + context.getBeanDefinitionCount());
assertThat(controllers).isZero();
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(ShipmentJsonTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
}
});
}
}
written: {"tracking_id":"TRK-7","shipped":"2026-03-09"}
writesSnakeCaseAndIsoDates(): SUCCESSFUL
read: Shipment[trackingId=TRK-8, shipped=2026-03-10]
readsJsonBack(): SUCCESSFUL
controllers in the context: 0, beans in total: 34
loadsOnlyTheJsonPartOfTheApplication(): SUCCESSFUL
- The record's
was written astrackingId , because oftracking_id , and the@JsonProperty as the ISO stringLocalDate . Jackson 3, which Spring Boot 4 uses, writes dates as strings by default. Plain Jackson 2 wrote numeric timestamps unless configured otherwise, a setting Spring Boot used to change for you.2026-03-09 read JSON back into the record, so both directions are tested.parseObject- The context held 34 beans and no controller, although
is in the same package. The slice ignores component scanning for anything that is not JSON-related.ShipmentController
The annotation @JsonPropertycom.fasterxml.jackson.annotationtools.jackson
The two most used slices are @WebMvcTest@DataJpaTestspring-boot-webmvc-testspring-boot-data-jpa-test@JsonTest
@WebMvcTest@Component
package demo.testing.webmvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.test.web.servlet.assertj.MvcTestResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
public class WebMvcSliceTest {
record Order(long id, String sku, int quantity) {
}
@SpringBootApplication
static class ShopApplication {
}
@Service
static class OrderService {
Order find(long id) {
throw new UnsupportedOperationException("talks to the database");
}
}
@Component
static class NightlyReport {
}
@RestController
static class OrderController {
private final OrderService orders;
OrderController(OrderService orders) {
this.orders = orders;
}
@GetMapping("/orders/{id}")
Order get(@PathVariable long id) {
return orders.find(id);
}
}
@RestControllerAdvice
static class ErrorAdvice {
@ExceptionHandler(IllegalArgumentException.class)
ResponseEntity<Map<String, String>> badRequest(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
}
}
@WebMvcTest(controllers = OrderController.class,
properties = {"spring.main.banner-mode=off", "logging.level.root=WARN"})
static class OrderControllerSliceTest {
@Autowired
MockMvcTester mvc;
@MockitoBean
OrderService orders;
@Autowired
ApplicationContext context;
@Test
void returnsTheOrder() throws Exception {
given(orders.find(1)).willReturn(new Order(1, "book", 2));
MvcTestResult result = mvc.get().uri("/orders/1").exchange();
System.out.println(" GET /orders/1 -> " + result.getResponse().getStatus() + " "
+ result.getResponse().getContentAsString());
assertThat(result).hasStatusOk()
.bodyJson().extractingPath("$.sku").isEqualTo("book");
}
@Test
void adviceTurnsExceptionsInto400() throws Exception {
given(orders.find(-1)).willThrow(new IllegalArgumentException("id must be > 0"));
MvcTestResult result = mvc.get().uri("/orders/-1").exchange();
System.out.println(" GET /orders/-1 -> " + result.getResponse().getStatus() + " "
+ result.getResponse().getContentAsString());
assertThat(result).hasStatus(HttpStatus.BAD_REQUEST);
}
@Test
void loadsOnlyTheWebLayer() {
System.out.println(" OrderController beans: "
+ context.getBeanNamesForType(OrderController.class).length
+ ", ErrorAdvice beans: "
+ context.getBeanNamesForType(ErrorAdvice.class).length
+ ", NightlyReport beans: "
+ context.getBeanNamesForType(NightlyReport.class).length);
System.out.println(" OrderService is a mock: "
+ Mockito.mockingDetails(context.getBean(OrderService.class)).isMock()
+ ", beans in total: " + context.getBeanDefinitionCount());
assertThat(context.getBeanNamesForType(NightlyReport.class)).isEmpty();
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(OrderControllerSliceTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
}
});
}
}
GET /orders/-1 -> 400 {"error":"id must be > 0"}
adviceTurnsExceptionsInto400(): SUCCESSFUL
OrderController beans: 1, ErrorAdvice beans: 1, NightlyReport beans: 0
OrderService is a mock: true, beans in total: 125
loadsOnlyTheWebLayer(): SUCCESSFUL
GET /orders/1 -> 200 {"id":1,"sku":"book","quantity":2}
returnsTheOrder(): SUCCESSFUL
returned the order that the test stubbed on the mock. The realGET /orders/1 would have thrown, so the response proves the controller got the mock.OrderService.find returned 400 withGET /orders/-1 : the{"error":"id must be > 0"} is part of the slice and turned the stubbed exception into a response.@RestControllerAdvice- The context held one
and oneOrderController , but noErrorAdvice . WithoutNightlyReport , the context would fail to start, because the controller's@MockitoBean is not in the slice.OrderService - The slice still had 125 beans: message converters, Jackson, validation, the
setup and the rest of Spring MVC. What it leaves out is your service, data and scheduling code, and the embedded server.MockMvc
@DataJpaTest
package demo.testing.datajpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.sql.Connection;
import java.util.List;
import javax.sql.DataSource;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.jpa.test.autoconfigure.TestEntityManager;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
public class DataJpaSliceTest {
@Entity
@Table(name = "orders")
public static class OrderEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
Long id;
@Column(unique = true)
String reference;
String sku;
protected OrderEntity() {
}
OrderEntity(String reference, String sku) {
this.reference = reference;
this.sku = sku;
}
}
interface OrderRepository extends JpaRepository<OrderEntity, Long> {
List<OrderEntity> findBySku(String sku);
}
@SpringBootApplication
@EnableJpaRepositories(considerNestedRepositories = true) // OrderRepository is nested
static class ShopApplication {
}
@DataJpaTest(properties = {"spring.main.banner-mode=off", "logging.level.root=WARN"})
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
static class OrderRepositoryTest {
@Autowired
OrderRepository repository;
@Autowired
TestEntityManager entityManager;
@Autowired
DataSource dataSource;
@Test
@Order(1)
void usesAnEmbeddedDatabase() throws Exception {
try (Connection connection = dataSource.getConnection()) {
String url = connection.getMetaData().getURL();
System.out.println(" database: "
+ connection.getMetaData().getDatabaseProductName()
+ ", in memory: " + url.startsWith("jdbc:h2:mem:"));
}
}
@Test
@Order(2)
void findsOrdersBySku() {
repository.save(new OrderEntity("A-1", "book"));
repository.save(new OrderEntity("A-2", "pen"));
entityManager.flush();
entityManager.clear(); // forget the saved objects: the query must hit the table
List<OrderEntity> books = repository.findBySku("book");
System.out.println(" findBySku(book) -> " + books.size() + " row");
assertThat(books).hasSize(1);
}
@Test
@Order(3)
void previousTestWasRolledBack() {
System.out.println(" count() -> " + repository.count());
assertThat(repository.count()).isZero();
}
@Test
@Order(4)
void duplicatePassesWithoutFlush() {
repository.save(new OrderEntity("B-1", "book"));
repository.save(new OrderEntity("B-1", "pen")); // same unique reference
System.out.println(" two orders with reference B-1 saved, no error");
}
@Test
@Order(5)
void duplicateFailsOnFlush() {
repository.save(new OrderEntity("C-1", "book"));
assertThatThrownBy(() -> repository.saveAndFlush(new OrderEntity("C-1", "pen")))
.isInstanceOf(DataIntegrityViolationException.class);
System.out.println(" saveAndFlush threw DataIntegrityViolationException");
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(OrderRepositoryTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> System.out.println(" " + t));
}
}
});
}
}
Hibernate: create global temporary table HTE_orders(rn_ integer not null, id bigint, reference varchar(255), sku varchar(255), primary key (rn_)) transactional
Hibernate: drop table if exists orders cascade
Hibernate: drop sequence if exists orders_seq
Hibernate: create sequence orders_seq start with 1 increment by 50
Hibernate: create table orders (id bigint not null, reference varchar(255) unique, sku varchar(255), primary key (id))
database: H2, in memory: true
usesAnEmbeddedDatabase(): SUCCESSFUL
Hibernate: select next value for orders_seq
Hibernate: select next value for orders_seq
Hibernate: insert into orders (reference,sku,id) values (?,?,?)
Hibernate: insert into orders (reference,sku,id) values (?,?,?)
Hibernate: select oe1_0.id,oe1_0.reference,oe1_0.sku from orders oe1_0 where oe1_0.sku=?
findBySku(book) -> 1 row
findsOrdersBySku(): SUCCESSFUL
Hibernate: select count(*) from orders oe1_0
count() -> 0
Hibernate: select count(*) from orders oe1_0
previousTestWasRolledBack(): SUCCESSFUL
two orders with reference B-1 saved, no error
duplicatePassesWithoutFlush(): SUCCESSFUL
Hibernate: insert into orders (reference,sku,id) values (?,?,?)
Hibernate: insert into orders (reference,sku,id) values (?,?,?)
WARN org.hibernate.orm.jdbc.error - HHH000247: ErrorCode: 23505, SQLState: 23505
WARN org.hibernate.orm.jdbc.error - Unique index or primary key violation: "PUBLIC.CONSTRAINT_8B INDEX PUBLIC.CONSTRAINT_INDEX_8 ON PUBLIC.ORDERS(REFERENCE NULLS FIRST) VALUES ( /* 5 */ 'C-1' )"; SQL statement:
insert into orders (reference,sku,id) values (?,?,?) [23505-240]
saveAndFlush threw DataIntegrityViolationException
duplicateFailsOnFlush(): SUCCESSFUL
Hibernate: drop table if exists orders cascade
Hibernate: drop sequence if exists orders_seq
- The schema was created from the entity: a sequence with
and a table with aincrement by 50 column. Theunique table is a helper Hibernate creates for bulk updates and deletes.HTE_orders - The data source was an in-memory H2 database.
replaced whatever data source the application configures, through@DataJpaTest .@AutoConfigureTestDatabase - In
, the two inserts ran atfindsOrdersBySku , andentityManager.flush() made the derived query read from the table. It found 1 row.clear() - The next test counted 0 rows: the inserts of the previous test were rolled back.
saved two orders with the same unique reference and passed. NoduplicatePassesWithoutFlush appears in its output: with a sequence id, Hibernate only queues the inserts, and the rollback discarded them. The test proves nothing about the constraint.insert sent both inserts, H2 rejected the second with error 23505, and Spring translated it intosaveAndFlush . Flush before asserting whenever the database is what you are testing.DataIntegrityViolationException
The repository is a nested interface only to keep the program in one file, which is why the application needs considerNestedRepositories = true@AutoConfigureTestDatabase(replace = Replace.NONE)
Other slices follow the same pattern, each from its own module in Spring Boot 4: @WebFluxTestspring-boot-webflux-test@JdbcTestspring-boot-jdbc-test@DataJdbcTestspring-boot-data-jdbc-test@RestClientTestspring-boot-restclient-test
Reading a failing test
Two kinds of failure look very different: an assertion that does not hold, and a context that cannot start. This program has one of each. The second test class forgets to activate the prodTaxRates
package demo.testing.failing;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
public class FailingTests {
interface TaxRates {
int percent();
}
@SpringBootApplication
static class ShopApplication {
}
// TaxRates exists only in the "prod" profile
@Configuration
@Profile("prod")
static class ProdConfig {
@Bean
TaxRates taxRates() {
return () -> 20;
}
}
@RestController
static class TaxController {
private final TaxRates rates;
TaxController(TaxRates rates) {
this.rates = rates;
}
@GetMapping("/tax")
String tax() {
return "{\"percent\": " + rates.percent() + "}";
}
}
@SpringBootTest(properties = "spring.main.banner-mode=off")
@ActiveProfiles("prod")
static class WrongExpectationTest {
@Autowired
WebApplicationContext context;
@Test
void taxIsTwentyOnePercent() {
assertThat(MockMvcTester.from(context).get().uri("/tax"))
.hasStatusOk().bodyJson().extractingPath("$.percent").isEqualTo(21);
}
}
@SpringBootTest(properties = {"spring.main.banner-mode=off",
"logging.level.org.springframework=ERROR",
"spring.test.print-condition-evaluation-report=false"})
static class MissingProfileTest {
@Test
void contextStarts() {
}
}
public static void main(String[] args) {
LauncherFactory.create().execute(
LauncherDiscoveryRequestBuilder.request()
.selectors(DiscoverySelectors.selectClass(WrongExpectationTest.class),
DiscoverySelectors.selectClass(MissingProfileTest.class))
.build(),
new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult result) {
if (id.isTest()) {
System.out.println(id.getDisplayName() + ": " + result.getStatus());
result.getThrowable().ifPresent(t -> {
// the context message continues with the whole merged test
// configuration, including an identity hash that changes per run
String message = t.toString().strip();
int cut = message.indexOf(" for [");
System.out.println(" " + (cut > 0
? message.substring(0, cut) + " for [...]" : message));
Throwable root = t;
while (root.getCause() != null) {
root = root.getCause();
}
if (root != t) {
System.out.println(" root cause: " + root.getMessage());
}
});
}
}
});
}
}
WARN o.s.b.j.a.JpaBaseConfiguration$JpaWebConfiguration - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
taxIsTwentyOnePercent(): FAILED
org.opentest4j.AssertionFailedError:
expected: 21
but was: 20
ERROR o.s.b.d.LoggingFailureAnalysisReporter -
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in demo.testing.failing.FailingTests$TaxController required a bean of type 'demo.testing.failing.FailingTests$TaxRates' that could not be found.
Action:
Consider defining a bean of type 'demo.testing.failing.FailingTests$TaxRates' in your configuration.
contextStarts(): FAILED
java.lang.IllegalStateException: Failed to load ApplicationContext for [...]
root cause: No qualifying bean of type 'demo.testing.failing.FailingTests$TaxRates' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
- The assertion failure is short and exact: AssertJ read
from the response and reported$.percent butexpected: 21 .was: 20 - The context failure first printed Spring Boot's failure analysis, the same "APPLICATION FAILED TO START" report a real start-up prints. It names the constructor parameter that needed a
bean, which is usually enough to find the problem.TaxRates - The test itself then failed with
. The useful part is the root cause at the bottom of the chain, which says that no qualifying bean of typeIllegalStateException: Failed to load ApplicationContext is available.TaxRates
Two settings in the program keep this output short. logging.level.org.springframework=ERRORspring.test.print-condition-evaluation-report=false
A context that fails to start is also cached as a failure. Every later test class with the same configuration fails at once with the same error, instead of trying to start it again. Fix the first failure in the report, and the others usually go with it.
Test dependencies in Spring Boot 4
Spring Boot 4 split its test support into one module per technology, which changes the build file of every project that upgrades:
- Test starters: each starter has a test companion, such as
forspring-boot-starter-webmvc-test . It brings inspring-boot-starter-webmvc (JUnit, AssertJ, Mockito, JSONassert, Awaitility) and the module with that technology's slice annotations.spring-boot-starter-test - New packages:
moved to@WebMvcTest ,org.springframework.boot.webmvc.test.autoconfigure to@DataJpaTest , and so on. Imports from the Boot 3 packages no longer compile.org.springframework.boot.data.jpa.test.autoconfigure - Removed annotations:
and@MockBean are gone; use@SpyBean and@MockitoBean .@MockitoSpyBean - Opt-in clients: a
test no longer gets aRANDOM_PORT orWebTestClient by itself. AddTestRestTemplate ,@AutoConfigureWebTestClient or@AutoConfigureRestTestClient , just as MockMvc has always needed@AutoConfigureTestRestTemplate .@AutoConfigureMockMvc - JUnit 6:
4.1 brings JUnit Jupiter 6.0, as the program output above was produced with. Tests written for JUnit 5 run unchanged in nearly all cases.spring-boot-starter-test
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa-test</artifactId>
<scope>test</scope>
</dependency>
Choosing the kind of test
| Question the test answers | Kind of test |
|---|---|
| Is the business rule right? | Plain unit test with Mockito, no Spring |
| Does the controller map the URL, read the body and return the right status? | @WebMvcTestMockMvcTester@MockitoBean |
| Does the query in a repository return the right rows? | @DataJpaTest@JdbcTestJdbcTemplate |
| Is a class written and read as the expected JSON? | @JsonTestJacksonTester |
| Does a request work through every layer? | @SpringBootTest@AutoConfigureMockMvc |
| Do filters, error pages and the real HTTP stack behave? | @SpringBootTest(webEnvironment = RANDOM_PORT)RestTestClient |
| Does the application work against a real database or broker? | @SpringBootTest |
A healthy suite has many unit tests, a fair number of slice tests and a few full-context tests, and keeps the full-context ones on a small number of shared configurations so the context cache can do its work. Context caching, @TestConfiguration