Spring Boot & Spring Cloud

Testing Spring Boot 3 Applications: Slices, MockMvc, Testcontainers and Context Caching

Intermediate7 min readUpdated

You will be able to test a Spring Boot 3 service at the right level for each concern: plain unit tests for logic, @WebMvcTest with MockMvc for controllers, @DataJpaTest against a real database in Testcontainers for repositories, @SpringBootTest for end-to-end checks, and the context-caching and bean-override rules that keep the whole suite fast and honest.

What you will learn

  • Choose between a unit test, a test slice and a full @SpringBootTest for a given piece of code
  • Test controllers, validation and error responses with @WebMvcTest and MockMvc
  • Run repository tests against a real database with @DataJpaTest and Testcontainers @ServiceConnection
  • Replace collaborators with @MockitoBean and understand how bean overrides affect context caching
  • Write end-to-end tests with @SpringBootTest, a random port and a real HTTP client
  • Keep a growing test suite fast by controlling the number of distinct application contexts

A Spring Boot service has several kinds of code with different failure modes: business rules that can be wrong, controllers that can map JSON or status codes incorrectly, queries that can be invalid for the real database, and configuration that can wire the wrong bean. One kind of test does not fit all of them. Booting the whole application for every check makes the suite slow and the failures vague; mocking everything makes it fast and meaningless. This page lays out a layered approach on Spring Boot 3 with JUnit 5 and the tools spring-boot-starter-test brings in, and explains the context-caching mechanics that decide whether a suite of five hundred tests runs in twenty seconds or ten minutes.

What the test starter gives you

spring-boot-starter-test bundles JUnit Jupiter, AssertJ, Mockito, Hamcrest, JSONassert, JsonPath, Awaitility and Spring's own test support (spring-test, spring-boot-test, spring-boot-test-autoconfigure). The starter has not included the JUnit 4 vintage engine since Boot 2.4; tests use @Test from org.junit.jupiter.api, and the old @RunWith(SpringRunner.class) is replaced by the extension that @SpringBootTest and the slices already declare.

The layers, from fastest and most focused to slowest and broadest:

LevelAnnotationStartsUse for
UnitnonenothingDomain logic, mappers, calculations
Web slice@WebMvcTestMVC infrastructure + selected controllersRequest mapping, JSON, validation, error responses, security rules
Data slice@DataJpaTestJPA, repositories, a databaseQueries, mappings, migrations
Other slices@JsonTest, @RestClientTest, @DataJdbcTest, @WebFluxTest…one concern eachSerialisation, HTTP clients
Full context@SpringBootTesteverything, optionally a real serverWiring, end-to-end flows, configuration

The rule of thumb: push each check to the lowest level that can prove it. A rounding rule does not need Spring; a status code does not need a database; a JPQL query does need a database but not Tomcat.

Unit tests: no container required

Because Boot applications use constructor injection, most classes can be instantiated directly:

class PricingServiceTest {

    private final TaxRates rates = mock(TaxRates.class);
    private final PricingService pricing = new PricingService(rates);

    @Test
    void appliesReducedRateToBooks() {
        when(rates.rateFor(Category.BOOKS)).thenReturn(new BigDecimal("0.055"));

        Money total = pricing.priceWithTax(new Item("ISBN-1", Category.BOOKS, Money.of("20.00")));

        assertThat(total).isEqualTo(Money.of("21.10"));
        verifyNoMoreInteractions(rates);
    }
}

Nothing here is Spring-specific, and that is the point. If a class is hard to construct in a test, the cause is usually field injection or a dependency on the ApplicationContext; fix the design rather than reaching for @SpringBootTest. Mockito's @ExtendWith(MockitoExtension.class) with @Mock and @InjectMocks removes the boilerplate when there are several collaborators.

Controllers with @WebMvcTest

@WebMvcTest(OrderController.class) builds a context containing only the web layer and the named controller, auto-configures MockMvc, and expects you to supply the controller's dependencies:

@WebMvcTest(OrderController.class)
class OrderControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean OrderService orders;

    @Test
    void returnsOrderAsJson() throws Exception {
        when(orders.get(42L)).thenReturn(sampleOrder(42L));

        mvc.perform(get("/api/orders/42").accept(MediaType.APPLICATION_JSON))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.id").value(42))
           .andExpect(jsonPath("$.lines", hasSize(2)));
    }

    @Test
    void rejectsInvalidBodyWithProblemDetail() throws Exception {
        mvc.perform(post("/api/orders")
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                        {"customerId": null, "lines": []}
                        """))
           .andExpect(status().isBadRequest())
           .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
           .andExpect(jsonPath("$.errors[*].field", containsInAnyOrder("customerId", "lines")));
        verifyNoInteractions(orders);
    }

    @Test
    void mapsDomainExceptionTo404() throws Exception {
        when(orders.get(7L)).thenThrow(new OrderNotFoundException(7L));

        mvc.perform(get("/api/orders/7"))
           .andExpect(status().isNotFound())
           .andExpect(jsonPath("$.title").value("Order not found"));
    }
}

MockMvc drives the DispatcherServlet directly without a socket, so the test exercises argument resolution, validation, message conversion, @RestControllerAdvice and filters, exactly the things unit tests of the controller class would miss. From Boot 3.4 (Spring Framework 6.2) MockMvcTester offers the same in an AssertJ style: assertThat(mvc.get().uri("/api/orders/42")).hasStatusOk().bodyJson().extractingPath("$.id").isEqualTo(42).

With Spring Security on the classpath, the slice includes the security configuration, so unauthenticated requests get 401 unless you add @WithMockUser from spring-security-test or attach a jwt() post-processor; that is a feature, since it lets you test authorisation rules per endpoint without a token server.

Repositories with @DataJpaTest and Testcontainers

@DataJpaTest configures JPA, Spring Data repositories, a TestEntityManager, and makes every test transactional with rollback at the end, so tests do not see each other's data. By default it swaps the DataSource for an embedded database, which is convenient and misleading; point it at the engine you deploy on instead:

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired OrderRepository orders;
    @Autowired TestEntityManager em;

    @Test
    void findWithLinesFetchesLinesInOneQuery() {
        Order order = em.persistFlushFind(orderWithLines(3));
        em.clear();                                  // detach so the next load hits the database

        Optional<Order> loaded = orders.findWithLines(order.getId());

        assertThat(loaded).isPresent();
        assertThat(loaded.get().getLines()).hasSize(3);   // no LazyInitializationException: fetch join worked
    }

    @Test
    void expireStaleOrdersOnlyTouchesNewOrders() {
        em.persist(order(OrderStatus.NEW, daysAgo(10)));
        em.persist(order(OrderStatus.SHIPPED, daysAgo(10)));
        em.flush();

        int updated = orders.expireStaleOrders(OrderStatus.EXPIRED, Instant.now().minus(7, DAYS));

        assertThat(updated).isEqualTo(1);
    }
}

@ServiceConnection (Boot 3.1+) reads the container's host, port and credentials and configures the DataSource from them, replacing the older @DynamicPropertySource method that set spring.datasource.url by hand. Flyway runs against the container as it would in production, so the test also proves the migrations. A static container is started once per test class; to share one across the whole suite, declare it in a @TestConfiguration class imported by every test, or use the Testcontainers reuse feature.

Because the slice rolls back after each test, code that relies on commit-time behaviour (@TransactionalEventListener, SEQUENCE allocation, database triggers) will not fire. Annotate a specific test with @Transactional(propagation = NOT_SUPPORTED) or @Commit when that behaviour is what you are testing, and clean up explicitly.

End-to-end with @SpringBootTest

When the question is "does the whole thing work together", start the whole thing:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class OrderFlowTest {

    @Container @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired TestRestTemplate http;              // pre-configured with the random port
    @MockitoBean PaymentGateway gateway;           // the one dependency that must not be real

    @Test
    void placingAnOrderReturns201AndPersistsIt() {
        when(gateway.charge(any())).thenReturn(Payment.approved("txn-1"));

        ResponseEntity<OrderResponse> response = http.postForEntity("/api/orders",
                new CreateOrderRequest(1L, List.of(new OrderLine("ABC-12345", 2))), OrderResponse.class);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(response.getHeaders().getLocation()).hasPath("/api/orders/" + response.getBody().id());

        ResponseEntity<OrderResponse> fetched = http.getForEntity(response.getHeaders().getLocation(), OrderResponse.class);
        assertThat(fetched.getBody().status()).isEqualTo("PAID");
    }
}

RANDOM_PORT starts the embedded server on a free port and makes TestRestTemplate (or WebTestClient, if WebFlux is on the classpath) available with the base URL set. The default MOCK environment starts the context without a server and lets you use MockMvc with @AutoConfigureMockMvc, which is faster and enough when the network layer is not the subject.

@SpringBootTest finds the @SpringBootConfiguration class by walking up the package tree from the test, which is why the application class sits in the root package. Properties for the test go in properties = "..." on the annotation, a src/test/resources/application-test.yml activated with @ActiveProfiles("test"), or @TestPropertySource; the first two are the least surprising.

Keep the number of these tests small and their scope wide. Each one that covers a realistic user flow is worth more than ten that duplicate what slices already verify.

Replacing beans and the cost of doing so

@MockitoBean replaces (or adds) a bean in the context with a Mockito mock that is reset after every test method; @MockitoSpyBean wraps the real bean. Both come from Spring Framework 6.2 and supersede Boot's @MockBean/@SpyBean, deprecated in 3.4. For anything more elaborate than a mock, a @TestConfiguration class with @Bean methods, imported with @Import or nested static in the test, provides a hand-written fake and is often clearer than stubbing a dozen calls.

The price of overriding is paid in context starts. Spring caches application contexts across test classes keyed on their configuration: the configuration classes, the active profiles, the properties, the set of overridden beans, the web environment, and more. Two test classes with identical keys share one context; any difference means another full start-up. A suite where every class declares its own @MockitoBean fields creates nearly one context per class and spends most of its time booting Spring.

Habits that keep the count low:

  • Define shared mocks and fakes once in a base test class or a common @TestConfiguration, and reuse the same annotation set across classes.
  • Avoid @DirtiesContext except when a test genuinely corrupts shared state; it throws the context away.
  • Put test properties in one profile rather than in per-class properties attributes.
  • Use slices; a @WebMvcTest context starts in a fraction of the time of the full one and is cached separately.

To see what is happening, count the Boot banners (or the "Started … in x seconds" lines) in the test log; logging.level.org.springframework.test.context.cache=DEBUG prints cache hits and misses.

Other slices worth knowing

@JsonTest builds only the Jackson configuration and gives you a JacksonTester<T> for round-tripping a DTO, useful for date formats and null handling. @RestClientTest(InventoryClient.class) configures a MockRestServiceServer bound to the auto-configured RestClient.Builder, so you can assert on outgoing requests and script responses without a network. @DataJdbcTest, @DataMongoTest, @DataRedisTest and @WebFluxTest follow the same pattern. Every slice accepts @Import for extra beans and excludeAutoConfiguration to trim what it loads.

For Spring Batch jobs, @SpringBatchTest adds JobLauncherTestUtils; for scheduled or asynchronous work, Awaitility's await().atMost(...).untilAsserted(...) replaces Thread.sleep in assertions.

Common mistakes

@SpringBootTest for everything. Slow suites, vague failures, and tests that pass because a mock somewhere returned null. Start at the unit level and move up only when the check needs more.

Mocking the repository in a service test and calling it an integration test. It proves nothing about the query. Repository behaviour needs @DataJpaTest with a real engine.

H2 in tests, PostgreSQL in production. Native queries, on conflict, JSON columns and sequence behaviour differ. Testcontainers removes the excuse.

Forgetting the slice does not include everything. A @WebMvcTest will not pick up a @Component converter or a @Service the controller needs; the error message lists the missing bean. Add it with @Import or a mock.

Asserting on getMessage() of exceptions or on log output. Both change with library versions. Assert on status codes, response bodies and persisted state.

A different @MockitoBean set in every class. Each combination is a new context. Consolidate.

Tests that depend on order or on leftover data. The data slice rolls back, but @SpringBootTest does not unless you add @Transactional, and Testcontainers databases persist for the class. Reset state explicitly, or make each test create what it needs with unique keys.

Key takeaways

  • Test each concern at the lowest level that can prove it: plain unit tests for logic, slices for the web and data layers, a few @SpringBootTest flows for wiring.
  • @WebMvcTest with MockMvc covers routing, JSON, validation, error responses and security rules without a server or a database.
  • @DataJpaTest with @AutoConfigureTestDatabase(replace = NONE) and a Testcontainers @ServiceConnection tests queries and migrations against the real database engine.
  • @MockitoBean replaces collaborators in the context; every distinct set of overrides, properties or profiles creates another cached context, so keep configurations uniform.
  • @SpringBootTest(webEnvironment = RANDOM_PORT) with TestRestTemplate gives true end-to-end checks; use them sparingly and make them count.
  • Watch context starts in the log; the number of contexts, not the number of tests, determines suite time.

Sources and further reading

Frequently asked questions

Why are my Spring Boot tests so slow?
Almost always because the suite starts many distinct application contexts. Spring caches a context and reuses it for every test class with the same configuration, but any difference (a different set of @MockitoBean fields, different properties, a different active profile, @DirtiesContext) creates a new one, and each start costs seconds. Consolidate mocks into shared test configuration, avoid per-class properties, and check the log for how many times the Boot banner appears.
What replaced @MockBean in Spring Boot 3.4?
@MockitoBean and @MockitoSpyBean from Spring Framework 6.2, in the org.springframework.test.context.bean.override.mockito package. Boot deprecated its own @MockBean and @SpyBean in 3.4 in favour of them. The behaviour is the same for most uses: the bean in the context is replaced by a Mockito mock that is reset after each test, and the override counts as a difference for context caching.
Should repository tests use H2 or the real database?
The real database engine, through Testcontainers. H2 tolerates SQL that PostgreSQL or MySQL rejects and lacks their types and functions, so a green H2 suite can hide a failing migration or native query. @DataJpaTest replaces your DataSource with an embedded one by default; disable that with @AutoConfigureTestDatabase(replace = NONE) and point it at a container with @ServiceConnection.
Does @WebMvcTest load my services and repositories?
No. It creates a context with only the web layer: controllers, controller advice, filters, converters, WebMvcConfigurer beans and Spring Security if present. Every service a controller depends on must be provided, usually as a @MockitoBean; if it is missing the context fails to start with an unsatisfied dependency error, which is the slice doing its job.