Spring Boot test slices and ApplicationContext caching
How @WebMvcTest, @DataJpaTest, and @JsonTest scope beans, how Spring TestContext builds cache keys, and why @MockBean and @DirtiesContext break reuse.
As our team project’s test suite grew, a single
./gradlew testrun started printing the Spring banner more than ten times. Here is how I narrowed bean loading with test slices and aligned Spring TestContext cache keys to cut redundant context startups.
Tested with Spring Boot 3.1.5 (Spring Framework 6.0.13), Kotlin 1.9.10, JUnit 5.9.3, and Gradle Kotlin DSL.
Background
When my team started building a study-room reservation service for a university project, I put @SpringBootTest on every test class out of habit. Once the suite crossed 60 tests, a full local run took over a minute, and the console logs showed Hibernate bootstrapping over and over again for almost every class.
Two separate issues caused the slowdown. First, controller tests were booting the entire JPA layer and database setup just to verify HTTP routing and JSON output. Second, every test class declared its own combination of @MockBean fields, which prevented Spring from reusing contexts it had already created. I fixed the first issue by moving layer-specific tests onto Spring Boot test slices, and I fixed the second by aligning the cache keys that Spring’s TestContext framework uses.
Choosing the right test slice
Spring Boot ships with slice annotations that load only the auto-configurations and beans needed for a single architectural layer. I use the following decision matrix when adding a new test:
| Annotation | Loaded beans & auto-configuration | Best fit | Trade-offs and caveats |
|---|---|---|---|
@SpringBootTest | Full application context and all auto-configurations | Cross-layer flows, transaction boundaries, end-to-end wiring | Slowest startup; cache keys split easily across classes |
@WebMvcTest | MVC layer (@Controller, @ControllerAdvice, Filter, WebMvcConfigurer) | Request mapping, validation errors, HTTP status, JSON shape | Does not load @Service beans; requires @MockBean |
@DataJpaTest | @Entity, Spring Data repositories, TestEntityManager | Query methods, entity mappings, database constraints | Replaces DataSource with an embedded DB by default; rolls back each test |
@JsonTest | ObjectMapper, @JsonComponent, Jackson modules | DTO field names, date formats, null handling | Verifies serialization only, without the web layer |
| Plain unit test | No Spring context at all | Domain calculations and pure business rules | Fastest option; always reach for this first |
Test slices aren’t a silver bullet. If you’re putting five @MockBean annotations on a @WebMvcTest just to test service logic, you’re fighting the framework—write a plain unit test with direct constructor injection instead. Likewise, @DataJpaTest swaps out your real database for an embedded one like H2 by default. A query that uses PostgreSQL-specific syntax or jsonb operators can pass or behave differently on H2 and still fail in production, so don’t treat a passing @DataJpaTest as proof that native database queries work against your production engine.
Project setup and slice test examples
All three slice annotations come bundled in spring-boot-starter-test. For Kotlin JPA entities, I also enabled plugin.jpa. I covered entity design and compiler plugin configuration separately in Kotlin JPA entity design with all-open and no-arg plugins.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// build.gradle.kts
plugins {
id("org.springframework.boot") version "3.1.5"
id("io.spring.dependency-management") version "1.1.3"
kotlin("jvm") version "1.9.10"
kotlin("plugin.spring") version "1.9.10"
kotlin("plugin.jpa") version "1.9.10"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly("com.h2database:h2")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<Test> {
useJUnitPlatform()
}
Here is the minimal reservation domain used across the examples below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// src/main/kotlin/com/example/studyroom/reservation/Reservation.kt
package com.example.studyroom.reservation
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@Entity
class Reservation(
val room: String,
val headCount: Int,
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
)
interface ReservationRepository : JpaRepository<Reservation, Long> {
fun findAllByRoom(room: String): List<Reservation>
}
data class ReservationResponse(val id: Long, val room: String, val headCount: Int)
@Service
class ReservationService(private val repository: ReservationRepository) {
fun find(id: Long): ReservationResponse {
val r = repository.findById(id).orElseThrow()
return ReservationResponse(r.id!!, r.room, r.headCount)
}
}
@RestController
@RequestMapping("/api/reservations")
class ReservationController(private val reservationService: ReservationService) {
@GetMapping("/{id}")
fun find(@PathVariable id: Long): ReservationResponse = reservationService.find(id)
}
With that domain in place, each layer gets a focused slice test. Spring Boot 3.1 ships with Mockito 5, which uses the inline mock maker by default—meaning @MockBean can mock Kotlin’s final classes without extra configuration or open modifiers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// src/test/kotlin/com/example/studyroom/reservation/ReservationSliceTests.kt
package com.example.studyroom.reservation
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.BDDMockito.given
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.json.JsonTest
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.json.JacksonTester
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
@WebMvcTest(ReservationController::class)
class ReservationControllerTest(@Autowired val mockMvc: MockMvc) {
@MockBean
lateinit var reservationService: ReservationService
@Test
fun `returns 200 and body when fetching a single reservation`() {
given(reservationService.find(1L)).willReturn(ReservationResponse(1L, "Seminar Room A", 4))
mockMvc.get("/api/reservations/1").andExpect {
status { isOk() }
jsonPath("$.room") { value("Seminar Room A") }
}
}
}
@DataJpaTest
class ReservationRepositoryTest(
@Autowired val reservationRepository: ReservationRepository,
@Autowired val em: TestEntityManager,
) {
@Test
fun `finds reservations by room name`() {
em.persist(Reservation(room = "Seminar Room A", headCount = 4))
em.flush()
em.clear()
assertThat(reservationRepository.findAllByRoom("Seminar Room A")).hasSize(1)
}
}
@JsonTest
class ReservationResponseJsonTest {
@Autowired
lateinit var json: JacksonTester<ReservationResponse>
@Test
fun `locks down response DTO JSON field names`() {
val content = json.write(ReservationResponse(1L, "Seminar Room A", 4))
assertThat(content).extractingJsonPathStringValue("$.room").isEqualTo("Seminar Room A")
assertThat(content).extractingJsonPathNumberValue("$.headCount").isEqualTo(4)
}
}
How ApplicationContext caching works under the hood
Internally, every slice annotation works in three steps. Take @WebMvcTest as an example: @BootstrapWith(WebMvcTestContextBootstrapper::class) switches the test bootstrapper, @TypeExcludeFilters(WebMvcTypeExcludeFilter::class) restricts component scanning to MVC beans, and meta-annotations like @AutoConfigureWebMvc import only the auto-configurations listed in META-INF/spring/...AutoConfigureWebMvc.imports via @ImportAutoConfiguration.
Before creating an ApplicationContext, Spring’s TestContext framework collects the test class’s metadata into a MergedContextConfiguration object. That object acts as the cache key. Its equals and hashCode methods account for configuration classes, active profiles, @TestPropertySource and properties attributes, parent context, context loader, and the set of ContextCustomizer instances.
flowchart TD
A["Run test class"] --> B["Build MergedContextConfiguration"]
B --> C{"Matching key in ContextCache?"}
C -->|"Hit"| D["Reuse existing ApplicationContext"]
C -->|"Miss"| E["Load new context and store it"]
E --> F["Evict LRU entry if over maxSize"]
The trap most teams miss is ContextCustomizer. @MockBean and @SpyBean are translated into a MockitoContextCustomizer, whose equality depends on the exact set of mock definitions declared on the test class. If test A mocks only ReservationService, while test B mocks ReservationService and SettlementService, their MockitoContextCustomizer instances won’t match—so Spring boots two separate contexts. The same applies to @WebMvcTest(controllers = ...): specifying different controller classes changes TypeExcludeFiltersContextCustomizer, creating a dedicated context for each controller test.
Spring stores cached contexts in a static DefaultContextCache, which means the cache is shared only within the same JVM process. Its capacity defaults to 32 and can be adjusted with spring.test.context.cache.maxSize. If you annotate a class or method with @DirtiesContext, Spring closes that context and removes it from the cache, forcing the next test to boot a fresh one from scratch.
Patterns that break the cache and how to fix them
Before refactoring anything, I turned on cache statistics logging in src/test/resources/application.yml to measure how many contexts were actually being created:
1
2
3
4
# src/test/resources/application.yml
logging:
level:
org.springframework.test.context.cache: debug
At the end of a test run, Spring prints a summary line like this:
1
Spring test ApplicationContext cache statistics: [DefaultContextCache@6d2a2560 size = 11, maxSize = 32, parentContextCount = 0, hitCount = 52, missCount = 11]
missCount equals the number of times Spring had to boot a brand-new ApplicationContext. In my project, missCount was 11—and most of those misses came from @WebMvcTest classes declaring slightly different controller lists and @MockBean fields.
To unify the cache key across web slice tests, I moved the @WebMvcTest annotation and shared mocks into a single abstract base class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/test/kotlin/com/example/studyroom/support/WebSliceTestSupport.kt
package com.example.studyroom.support
import com.example.studyroom.reservation.ReservationService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.test.web.servlet.MockMvc
@WebMvcTest
abstract class WebSliceTestSupport {
@Autowired
lateinit var mockMvc: MockMvc
// Declare every service dependency needed by controllers here to keep one shared cache key.
@MockBean
lateinit var reservationService: ReservationService
}
Each controller test simply extends the base class (class ReservationControllerTest : WebSliceTestSupport()). Because @WebMvcTest has no controllers attribute specified, Spring loads all controllers into one shared MVC context, so every service bean those controllers depend on must be mocked in WebSliceTestSupport. I also removed every @DirtiesContext annotation and relied on @DataJpaTest’s default transaction rollback or explicit @Transactional cleanup instead. That single change dropped missCount from 11 to 4 and noticeably shortened our local and CI test runs.
Cached contexts stay open until the test JVM exits. Raising
maxSizetoo high keeps multiple connection pools,@Scheduledtasks, and embedded server ports alive at the same time, which can trigger out-of-memory errors or unexpected background jobs. Also keep Gradle’smaxParallelForksandforkEveryin mind: each forked JVM maintains its own separateDefaultContextCache, which reduces overall cache reuse.
Summary
Test slices narrow what Spring has to boot, and cache key discipline makes sure you actually reuse the contexts you build. Here is the checklist I run through whenever I add tests to a Spring Boot project:
- Check whether plain unit tests without Spring are enough for pure domain calculations.
- Consolidate
@WebMvcTestand its@MockBeandeclarations into a shared base class. - Replace
@DirtiesContextwith transaction rollbacks or explicit test data cleanup wherever possible. - Monitor
missCountperiodically by enablingorg.springframework.test.context.cache: debug. - Avoid relying on H2-backed
@DataJpaTestalone to validate database-specific SQL syntax or types.