Test Slices: @WebMvcTest vs @DataJpaTest vs @SpringBootTest
Fast recall
Quick revision
Core answer
Whether you understand the purpose and cost of each slice and make deliberate choices rather than defaulting to @SpringBootTest everywhere
Using @SpringBootTest for all tests — this is the most common cause of slow test suites in Spring Boot projects
Explain context caching: Spring reuses contexts across test classes that have the same configuration, so mixing @MockBeans and slices strategically can dramatically cut suite time
Interview-ready guide
Interview answer
The decision tree is simple: business logic → plain Mockito with no Spring. Controller mapping → @WebMvcTest. JPA query → @DataJpaTest. JSON serialization → @JsonTest. Only use @SpringBootTest for cross-cutting integration tests.
Startup time is the hidden cost. @SpringBootTest takes 10-30 seconds. @WebMvcTest takes 2 seconds. @ExtendWith(MockitoExtension.class) is instant. 50 test classes using @SpringBootTest adds 25 minutes to CI. The same tests with slices add 3 minutes.
The nuance is context caching. Spring reuses cached contexts across test classes with identical configurations. Different @MockBean combinations create different cache keys, triggering new context startups. Standardizing mock combinations across test classes is the easiest way to speed up a large test suite.
Start with the narrowest annotation and widen only if the test fails to run without more context.
Test Slices: @WebMvcTest vs @DataJpaTest vs @SpringBootTest
Direct Answer
Choose @WebMvcTest when testing HTTP layer logic (routing, validation, serialisation, security) for a specific controller without needing real services or databases. Choose @DataJpaTest when testing repository queries, custom JPQL, and database constraints without the web layer. Choose @SpringBootTest when you genuinely need multiple layers working together — it's the most realistic but slowest option. Using the narrowest slice keeps tests fast and failure messages focused.
Common Mistakes & Pitfalls
Using @SpringBootTest for all tests — this is the most common cause of slow test suites in Spring Boot projects
Check your understanding
Answer these without looking back at the article.
- What other test slices does Spring Boot provide besides these three?
- How does Spring's context caching work and how can you inspect it?
- When would you use @TestConfiguration to add beans to a test context?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.