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.

CsCode.ioUpdated
Share

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 module, starts an application context for the test class and injects its beans into the test with @Autowired. Spring Boot adds @SpringBootTest, which builds that context the same way SpringApplication.run does: it finds your @SpringBootApplication class by searching upwards from the test's package, applies auto-configuration and reads application.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 classes in reasonable time, and why anything that changes the configuration, such as a different @MockitoBean, costs a new context. The advanced testing page measures this.

The kinds of test in a Spring Boot application
TestWhat it startsRelative speedBest for
Plain unit testNothing; you call newFastestBusiness logic in services and other plain classes
Slice test (@WebMvcTest, @DataJpaTest, @JsonTest)One layer of the applicationFastControllers, repositories or JSON mapping on their own
@SpringBootTest (mock web environment)The whole context, no serverSlowerRequests through every layer, with MockMvc
@SpringBootTest(webEnvironment = RANDOM_PORT)The whole context and a real serverSlowestReal 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 main method runs the tests with the JUnit Platform launcher and prints each result. In a real project, the test class lives under src/test/java and Maven or Gradle runs it; the test code itself is the same.

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 and passes in Mockito mocks:

Java
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));
                        }
                    }
                });
    }
}
Output
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 isEqualByComparingTo because BigDecimal.equals also compares the scale, so 37.50 and 37.5 would not be equal.
  • The second test checks both the exception and its absence of side effects: verify(orders, never()).save(any()) fails if the service saved something before throwing.

Constructor injection is what makes this possible. A class whose dependencies arrive through @Autowired fields cannot be built in a test without reflection or Spring. Mockito 5 needs a Java agent to create its mocks; without one it attaches itself and prints a warning that this will stop working in a future JDK. The program runs with -javaagent:mockito-core.jar, and Mockito's documentation shows how to add the same argument to the Maven Surefire or Gradle test configuration.

@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:

Java
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));
                        }
                    }
                });
    }
}
Output
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
  • @SpringBootTest found ShopApplication on its own: it searched the test's package for a @SpringBootConfiguration. No server started; the default web environment, MOCK, gives a web application context with a mock servlet environment.
  • GET /orders/1 returned 200 with the order as JSON, written by Jackson. extractingPath("$.sku") took one field out with a JSON path.
  • POST /orders returned 201, a Location header of /orders/2 and the new order. isLenientlyEqualTo compared only the fields in the expected JSON, so the generated id did not have to be listed.
  • GET /orders/99 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 the DispatcherServlet directly, so the servlet container's forward to Spring Boot's /error page never happens.
  • 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.

MockMvcTester, added in Spring Framework 6.2, wraps the older MockMvc in AssertJ assertions. MockMvcTester.from(context) builds it from the web application context. In a normal project, add @AutoConfigureMockMvc to the test class instead and inject MockMvcTester directly. The annotation comes from the spring-boot-webmvc-test module; this program builds the tester itself to show that nothing more than the context is needed.

The WARN line at the top appears because every program on this page shares one classpath, and the @DataJpaTest example in the slices section puts JPA on it. With JPA and Spring MVC together, Spring Boot warns that spring.jpa.open-in-view is on by default, which keeps a database session open while the response is written. Set it to false explicitly and the warning goes away.

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 throws if it is called, and the test replaces it in the context with a mock:

Java
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));
                        }
                    }
                });
    }
}
Output
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 PriceClient injected into the test, and into the controller, was a Mockito mock. The real class's unitPrice never ran, or the test would have failed with "no network in tests".
  • The first test stubbed the price, sent a request through MockMvc and got book costs 12.50. then(prices).should().unitPrice("book") checked that the controller really called the client.
  • The second test made no stubbing, and the same mock returned Optional.empty. Spring resets @MockitoBean mocks after each test method, so a stub cannot leak from one test into the next. Mockito returns an empty Optional, not null, for an unstubbed method that returns Optional.

@MockitoBean and @MockitoSpyBean are part of Spring Framework since 6.2. Spring Boot's older @MockBean and @SpyBean were deprecated in Boot 3.4 and removed in Boot 4.0, so tests that still use them no longer compile after an upgrade. The replacement is a rename in most tests. The difference to watch is that the new annotations work only on fields of the test class, not inside a @Configuration class.

Each set of @MockitoBean fields is part of the context's cache key. Ten test classes that each mock a different bean start ten contexts. Keeping the mocked beans the same across classes, for example in a shared base class, lets them share one.

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 starts the embedded Tomcat on a free port, and the test calls it over HTTP:

Java
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);
    }
}
Output
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
  • @LocalServerPort injected the port Tomcat picked. A random port lets several test runs, or several test contexts, run on one machine without clashing.
  • The first test checked the status, the Content-Type header and the body, which RestTestClient converted back into an Order and compared with 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, error and path. The body also has a timestamp, so the program prints only whether the stable fields are there.

RestTestClient is new in Spring Framework 7. It offers the same fluent assertions as WebTestClient, but runs on RestClient, so a Spring MVC application no longer needs the WebFlux dependency for its HTTP tests. TestRestTemplate still works, but since Spring Boot 4 it needs @AutoConfigureTestRestTemplate; Boot's own @AutoConfigureRestTestClient injects a RestTestClient already pointed at the server. Spring Boot 4.2 deprecates TestRestTemplate, so write new tests with RestTestClient.

The program ends with System.exit(0). The cached context, and with it Tomcat, stays open until the JVM ends, and a build tool's test JVM ends by itself once the tests finish. Note also that a test with a real server runs the request on a different thread from the test. A @Transactional test method therefore cannot roll back what the server wrote.

Test slices: one layer at a time

A slice test starts only the part of the application that one layer needs. @JsonTest is the smallest: it configures Jackson and the JSON testers, and nothing else. This record renames one field and contains a date, the two things that most often break in JSON:

Java
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));
                        }
                    }
                });
    }
}
Output
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 trackingId was written as tracking_id, because of @JsonProperty, and the LocalDate as the ISO string 2026-03-09. 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.
  • parseObject read JSON back into the record, so both directions are tested.
  • The context held 34 beans and no controller, although ShipmentController is in the same package. The slice ignores component scanning for anything that is not JSON-related.

The annotation @JsonProperty still comes from the com.fasterxml.jackson.annotation package. Jackson 3 moved its core classes to tools.jackson but kept the annotations where they were, so most model classes need no change.

The two most used slices are @WebMvcTest and @DataJpaTest, from the modules spring-boot-webmvc-test and spring-boot-data-jpa-test. Like @JsonTest, each loads only its own layer.

@WebMvcTest starts the MVC infrastructure and the controllers you name, without a server. This application also has a service that needs a database and an unrelated @Component:

Java
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));
                        }
                    }
                });
    }
}
Output
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
  • GET /orders/1 returned the order that the test stubbed on the mock. The real OrderService.find would have thrown, so the response proves the controller got the mock.
  • GET /orders/-1 returned 400 with {"error":"id must be > 0"}: the @RestControllerAdvice is part of the slice and turned the stubbed exception into a response.
  • The context held one OrderController and one ErrorAdvice, but no NightlyReport. Without @MockitoBean, the context would fail to start, because the controller's OrderService is not in the slice.
  • The slice still had 125 beans: message converters, Jackson, validation, the MockMvc setup and the rest of Spring MVC. What it leaves out is your service, data and scheduling code, and the embedded server.

@DataJpaTest starts JPA, Spring Data repositories and an embedded database, and runs every test in a transaction that is rolled back at the end. It turns on SQL logging by default, which shows when statements really run:

Java
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));
                        }
                    }
                });
    }
}
Output
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 increment by 50 and a table with a unique column. The HTE_orders table is a helper Hibernate creates for bulk updates and deletes.
  • The data source was an in-memory H2 database. @DataJpaTest replaced whatever data source the application configures, through @AutoConfigureTestDatabase.
  • In findsOrdersBySku, the two inserts ran at entityManager.flush(), and clear() made the derived query read from the table. It found 1 row.
  • The next test counted 0 rows: the inserts of the previous test were rolled back.
  • duplicatePassesWithoutFlush saved two orders with the same unique reference and passed. No insert 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.
  • saveAndFlush sent both inserts, H2 rejected the second with error 23505, and Spring translated it into DataIntegrityViolationException. Flush before asserting whenever the database is what you are testing.

The repository is a nested interface only to keep the program in one file, which is why the application needs considerNestedRepositories = true. To keep the real data source, for example a Testcontainers database, add @AutoConfigureTestDatabase(replace = Replace.NONE).

Other slices follow the same pattern, each from its own module in Spring Boot 4: @WebFluxTest (spring-boot-webflux-test), @JdbcTest (spring-boot-jdbc-test), @DataJdbcTest (spring-boot-data-jdbc-test) and @RestClientTest (spring-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 prod profile, so the only TaxRates bean does not exist:

Java
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());
                                }
                            });
                        }
                    }
                });
    }
}
Output
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 $.percent from the response and reported expected: 21 but 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 TaxRates bean, which is usually enough to find the problem.
  • The test itself then failed with IllegalStateException: Failed to load ApplicationContext. The useful part is the root cause at the bottom of the chain, which says that no qualifying bean of type TaxRates is available.

Two settings in the program keep this output short. logging.level.org.springframework=ERROR hides a warning that repeats the whole stack trace. spring.test.print-condition-evaluation-report=false turns off the condition evaluation report that Spring Boot prints after a context fails to start, which lists, for every auto-configuration, why it did or did not apply. Leave the report on when the cause is a missing auto-configured bean, because it shows which condition failed.

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 spring-boot-starter-webmvc-test for spring-boot-starter-webmvc. It brings in spring-boot-starter-test (JUnit, AssertJ, Mockito, JSONassert, Awaitility) and the module with that technology's slice annotations.
  • New packages: @WebMvcTest moved to org.springframework.boot.webmvc.test.autoconfigure, @DataJpaTest to org.springframework.boot.data.jpa.test.autoconfigure, and so on. Imports from the Boot 3 packages no longer compile.
  • Removed annotations: @MockBean and @SpyBean are gone; use @MockitoBean and @MockitoSpyBean.
  • Opt-in clients: a RANDOM_PORT test no longer gets a WebTestClient or TestRestTemplate by itself. Add @AutoConfigureWebTestClient, @AutoConfigureRestTestClient or @AutoConfigureTestRestTemplate, just as MockMvc has always needed @AutoConfigureMockMvc.
  • JUnit 6: spring-boot-starter-test 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.
XML
<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

Which test to write for which question
Question the test answersKind 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?@WebMvcTest with MockMvcTester and @MockitoBean services
Does the query in a repository return the right rows?@DataJpaTest, or @JdbcTest for JdbcTemplate code
Is a class written and read as the expected JSON?@JsonTest with JacksonTester
Does a request work through every layer?@SpringBootTest with @AutoConfigureMockMvc
Do filters, error pages and the real HTTP stack behave?@SpringBootTest(webEnvironment = RANDOM_PORT) with RestTestClient
Does the application work against a real database or broker?@SpringBootTest with Testcontainers

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, test properties, transactional tests and outgoing HTTP calls are on the advanced Spring testing page, and real databases in tests on the Testcontainers page. The controller code tested here is explained on the REST controller page.