Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 66 ยท Testing

Test Slices, Context Caching and Test Speed

Speed up Spring Boot tests: @JsonTest, @DataJpaTest, @RestClientTest, how the context cache keys work, @DirtiesContext cost, parallelism and flaky tests.

Test suites rarely get slow all at once. They get slow by accident: one more @MockitoBean here, a different property there, a @DirtiesContext that "fixed" a flaky test, and one day the build takes twelve minutes and nobody runs it locally. Almost always the cause is the same: Spring is building the application context again and again, because each test asked for a slightly different one.

This lesson explains the two ideas that decide test speed in a Boot project. Slices load only a part of the application, so each context is small. The context cache keeps built contexts and reuses them across test classes, so most contexts are built once. Once you know how the cache decides "same context or new one", you can keep a suite fast by design. It extends Testing Spring Boot Applications and Testing Controllers with MockMvc.

Spring cannot run on this site, so Spring test code is read-only. The TryIts model how a slice selects beans and how the cache keys contexts, using plain Java.

Two levers for fast tests

Slices Load only the layer under test.
Context cache Build once, reuse everywhere.
1 / 2

The slice family

You met @WebMvcTest. Boot offers a family of similar annotations, each loading the beans and auto-configuration for one layer. A selection (in Boot 4 some of these annotations live in new packages with the modular starters, so use your IDE's import suggestions):

Annotation Loads Typical use
@WebMvcTest controllers, advice, filters, converters, validation status codes, JSON, security rules
@DataJpaTest entities, repositories, an embedded or container database, transactions that roll back queries and mappings
@JsonTest Jackson ObjectMapper and your JSON components serialization of DTOs
@RestClientTest RestClient/RestTemplate builders plus a mock server clients that call other services
@DataJdbcTest, @JdbcTest JDBC repositories or JdbcClient and a database plain SQL access
@DataMongoTest, @DataRedisTest the matching Spring Data support non-relational stores
@WebFluxTest reactive controllers and routes, plus a WebTestClient endpoints written with WebFlux instead of MVC

All slices ignore your normal @Component, @Service and @Configuration beans unless a test imports them. That is the point: the context is small, and anything outside the layer is a gap you fill deliberately with a mock or an @Import.

Advantages and limits of slices

Slices are a trade. What you gain:

  • Speed. A slice loads a handful of beans, so it starts in about a second and, thanks to the context cache described below, is often shared between test classes.
  • Focus. A failure points at one layer: a @WebMvcTest that fails is about mapping, JSON or validation, not about the database.
  • Better maintainability. Each slice only sees its own layer, so tests do not break when an unrelated bean changes its constructor.

What you give up:

  • Gaps you must fill. Anything outside the slice is missing, so you add @MockitoBean, @Import or @TestConfiguration for each collaborator, and a forgotten one fails with NoSuchBeanDefinitionException.
  • No end-to-end proof. A web slice cannot tell you that the service and the database cooperate. Keep a few @SpringBootTest tests for that.
  • Mocks can lie. If a mocked service is stubbed differently from how the real one behaves, the slice passes while production fails.
  • One stack per test. @WebFluxTest and @WebMvcTest describe two different web stacks and are not combined in one test class; a slice that needs security must import the security configuration on purpose.

@WebFluxTest is the reactive twin of @WebMvcTest: it loads @Controller and @RestController beans written with Spring WebFlux (and RouterFunction routes) and gives you a WebTestClient to call them without a server:

Java
@WebFluxTest(GreetingController.class)
class GreetingControllerTest {

    @Autowired WebTestClient client;
    @MockitoBean GreetingService greetings;

    @Test
    void returnsTheGreeting() {
        when(greetings.greet("Ada")).thenReturn(Mono.just("Hello, Ada"));

        client.get().uri("/greet/Ada")
            .exchange()
            .expectStatus().isOk()
            .expectBody(String.class).isEqualTo("Hello, Ada");
    }
}

@JsonTest: serialization on its own

JSON mapping is easy to break (a renamed field, a changed date format) and rarely worth a web test. @JsonTest starts just the mapper configuration:

Java
@JsonTest
class OrderJsonTest {

    @Autowired JacksonTester<OrderResponse> json;

    @Test
    void writesTheContractFields() throws Exception {
        var order = new OrderResponse(7L, "book-1", Instant.parse("2026-01-15T10:00:00Z"));

        assertThat(json.write(order)).hasJsonPathNumberValue("$.id")
            .extractingJsonPathStringValue("$.createdAt").isEqualTo("2026-01-15T10:00:00Z");
    }

    @Test
    void readsARequest() throws Exception {
        var request = json.parse("{\"sku\":\"book-1\",\"quantity\":2}");
        assertThat(request).isEqualTo(new NewOrder("book-1", 2));
    }
}

@DataJpaTest and @RestClientTest

@DataJpaTest is covered in Testing the Data Layer: every test runs in a transaction that rolls back, and by default Boot swaps your database for an embedded one (turn that off with @AutoConfigureTestDatabase(replace = NONE) when you use Testcontainers).

@RestClientTest tests a class that calls another service, such as a client wrapper around RestClient (Calling Other Services). The slice gives you a MockRestServiceServer that returns canned responses, so you test the URL, headers, JSON mapping and error handling without any network:

Java
@RestClientTest(WeatherClient.class)
class WeatherClientTest {

    @Autowired WeatherClient client;
    @Autowired MockRestServiceServer server;

    @Test
    void parsesTheForecast() {
        server.expect(requestTo("https://weather.example/v1/forecast?city=Oslo"))
            .andRespond(withSuccess("{\"city\":\"Oslo\",\"celsius\":4}", MediaType.APPLICATION_JSON));

        assertThat(client.forecast("Oslo").celsius()).isEqualTo(4);
        server.verify();
    }
}

How a slice picks its beans

A slice is a filter on component scanning. It keeps only beans of certain kinds, and everything a kept bean needs but the filter dropped is missing: that is where "No qualifying bean" errors come from. The TryIt reproduces that with custom marker annotations on four classes, three slice definitions, and a dependency check driven by constructor parameters.

Java What each slice loads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: slices include beans by kind, so cross-layer dependencies must be mocked or imported. What is the stand-in: Boot's slices use TypeExcludeFilters and per-slice auto-configuration lists, not marker annotations on classes like these.

The context cache

Building an application context is the expensive part of a Spring test: scanning, bean creation, auto-configuration, possibly a database. So the Spring TestContext framework stores every context it builds in a cache and hands the same instance to any later test class that needs an identical one. The cache lives for the whole test JVM, in memory, with a default maximum of 32 contexts. When it is full, the least recently used context is evicted and closed.

"Identical" is defined by the cache key, which is built from the test's context configuration:

  • the configuration classes or locations (what @SpringBootTest, @WebMvcTest(X.class) or @Import select),
  • the active profiles (@ActiveProfiles),
  • property sources: @TestPropertySource, @DynamicPropertySource registrations, inlined properties = {...},
  • context customizers, which includes the set of @MockitoBean and @MockitoSpyBean definitions,
  • the web environment and other @SpringBootTest attributes,
  • the parent context, if any.

Change any of these and you get a different key, therefore a new context. This explains the most common slowdown: ten test classes, each with a different @MockitoBean field, produce ten contexts. The TryIt below keeps a small LRU cache with the same key idea and runs a realistic mixed suite so you can count the builds.

Java A context cache, keys and evictions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output from the top. Two test classes with the same key share a context. An extra mock creates a new key even though the configuration is otherwise identical. With only three slots, older contexts are evicted (the real default is 32, which is plenty for most projects). A @DirtiesContext test forces the next user to rebuild.

What makes suites slow, and what to do

@DirtiesContext. It closes the context after a class or method, so the next test pays the full build cost again. It is the biggest hammer in the toolbox. People reach for it when a test leaves state behind, but the state (rows, cache entries, static fields, mock stubs) should be cleaned up directly: roll back transactions, clear caches in @AfterEach, reset mocks (@MockitoBean resets after each test by default). Use @DirtiesContext only when the test truly changes the context itself, for example by modifying a singleton bean's configuration.

Mock sprawl. Many different @MockitoBean sets multiply contexts. Move shared mocks into a common base class or a @TestConfiguration so many test classes produce one key. Keep slices narrow: @WebMvcTest(UserController.class) and @WebMvcTest(OrderController.class) are two contexts by design, while a bare @WebMvcTest loads every controller once and shares one context, which can be faster overall when you have many controller tests.

Properties per class. @TestPropertySource(properties = ...) and different @DynamicPropertySource setups each make a new key. Put properties that every test needs in src/test/resources/application.yml or a shared profile, and keep per-test overrides rare.

Random ports in dynamic properties. A new Testcontainers container per class means new properties and a new context. Share the container as shown in Integration Tests with Testcontainers.

Too many full-context tests. Push checks down: logic in plain unit tests, mappings in slices. A rule of thumb: if the test does not need the whole application, it should not start it.

Measure first. Turn on logging.level.org.springframework.test.context.cache=DEBUG and the log prints cache statistics with hits, misses and size after each test class. A suite with many misses has a key problem; a suite with mostly hits but slow tests has a different problem (slow queries, sleeps, expensive setup). Build tools also report per-class times.

Parallelism

JUnit can run test classes or methods in parallel (junit.jupiter.execution.parallel.enabled=true in junit-platform.properties). Unit tests with no shared state parallelize well and shorten the build roughly in proportion to your cores. Spring context tests are trickier: the cache is thread-safe, but tests that share one context also share its database, caches and singleton state, so parallel tests can interfere. Safe options: parallelize pure unit tests, run slice tests that use their own rolled-back transactions concurrently with care, and keep full-stack tests sequential. Build-level parallelism, such as running several Maven or Gradle test forks, gives each fork its own JVM and its own cache, so there is no sharing problem, only more memory use.

Flaky tests

A flaky test passes and fails on the same code. In a Spring suite the usual culprits are:

  1. Shared state between tests: rows left in a shared database, a singleton cache, static fields, or a mock that was stubbed in another test. Clean up, or give each test unique data.
  2. Order dependence: a test only passes if another ran first. JUnit's method order is deterministic but not obvious, so never rely on it. Run the suite in a random order occasionally to flush these out (junit.jupiter.testmethod.order.default).
  3. Time and randomness: Instant.now(), UUID.randomUUID(), Thread.sleep. Inject a Clock, assert on shape rather than value, and use Awaitility (await().atMost(...).until(...)) for asynchronous results instead of fixed sleeps.
  4. Real network and external services: replace with mocks, MockRestServiceServer or containers.
  5. Parallelism over shared resources: serialize with @Isolated or @ResourceLock.

Do not hide flakiness with automatic retries as a first step; they make the suite slower and the cause stays. Find the shared state, and fix or isolate it.

A quick audit: run the suite once with cache debug logging, count the distinct contexts that were built, and for each one ask "what was different?". Often two or three base classes or one shared @TestConfiguration collapse a dozen contexts into three.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Ten test classes each declare a different @MockitoBean field but are otherwise identical. How many application contexts does Spring build?

    The mock definitions are context customizers and contribute to the key, so each distinct set produces a new context.
  2. 2. What is the main cost of @DirtiesContext?

    The cached context is removed. Clean up state directly (rollbacks, clearing caches) instead of discarding the whole context.
  3. 3. Which slice annotation fits a test of a class that wraps RestClient and calls another service?

    @RestClientTest provides the client beans and a MockRestServiceServer, so you can test requests and responses without a network.
  4. 4. A test passes alone but fails when the whole suite runs. What is the most likely cause?

    Shared state and order dependence are the usual causes. Isolate or clean up the state rather than retrying.
  5. 5. What happens when the context cache is full and a test needs a new context?

    The cache is LRU with a default maximum of 32 contexts, controlled by spring.test.context.cache.maxSize.

Summary

  • Slices (@WebMvcTest, @DataJpaTest, @JsonTest, @RestClientTest, and others) load one layer, so contexts are small and tests start quickly.
  • A slice filters beans by kind; anything outside it must be mocked with @MockitoBean or added with @Import.
  • Spring caches built contexts in an LRU cache (default 32) keyed by configuration, profiles, properties, mock definitions and similar settings.
  • Different mock sets, properties or profiles make new contexts; share them through base classes or common test configuration.
  • Avoid @DirtiesContext; clean state directly. Measure with cache debug logging before optimizing.
  • Parallelize pure unit tests, keep shared-context tests careful, and fix flaky tests by removing shared state, time and randomness.

Next: Actuator: Health, Metrics and Info.