What Are Test Slices
Fast recall
Quick revision
Core answer
Awareness of Spring Boot's built-in test infrastructure beyond @SpringBootTest and knowing when to use slices.
Using @SpringBootTest for everything, not knowing slice annotations exist, and ending up with unnecessarily slow tests.
Name multiple slices—@WebMvcTest, @DataJpaTest, @JsonTest, @RestClientTest—and explain what each loads and when to use it.
Interview-ready guide
Interview answer
A test slice limits Spring Boot scanning and auto-configuration to a supported technical area. WebMvcTest focuses on MVC controllers and web infrastructure; DataJpaTest focuses on JPA and is transactional by default; JsonTest focuses on JSON support. The exact context can still change through imports, security setup, properties, and bean overrides. When a controller collaborator is outside the MVC slice, I can provide it with current @MockitoBean, older Boot @MockBean, or import a small real configuration. I choose a slice because the boundary matches the behavior and avoids unrelated setup, not because it guarantees a fixed startup time.
What Are Test Slices
Direct Answer
A test slice limits Spring Boot component scanning and auto-configuration to a supported technical area. For example, @WebMvcTest focuses on MVC types and @DataJpaTest focuses on JPA. Imports, security, properties, and bean overrides can still change the context, so a slice is a focused boundary rather than a promise of one exact layer or speed.
Code Example
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired private MockMvc mockMvc;
@MockBean // mock the service layer — slices don't load it
private OrderService orderService;
@Test
void shouldReturnOrderDetails() throws Exception {
var order = new Order(1L, "Laptop", 1500.0);
when(orderService.getOrder(1L)).thenReturn(order);
mockMvc.perform(get("/orders/1"))
.andExpect(status().isOk()) // verifies HTTP 200
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.item").value("Laptop"));
}
}
Common Mistakes & Pitfalls
- Treating a slice as one exact bean list: Imports, properties, security, and test overrides can change the context.
- Combining unrelated slice annotations: Each slice selects its own bootstrap and auto-configuration. Choose one focused boundary or define a broader test deliberately.
- Assuming every absent collaborator needs a mock: Use @MockitoBean or older @MockBean for a controlled double, @Import for a small real component, or broader configuration when its behavior is required.
- Promising a fixed speed: A slice usually avoids unrelated setup, but measure the real suite.
Check your understanding
Answer these without looking back at the article.
- When using @WebMvcTest, how do you provide the service dependency?
- Can you use @DataJpaTest with a real PostgreSQL database instead of H2?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.