Spring / Spring Boot 4 Basics Interview Questions
How does Spring Boot 4 testing work with @SpringBootTest and test slices?
Spring Boot 4 provides a rich testing support framework. @SpringBootTest loads the full application context for integration tests, while test slice annotations load only a subset of the context for focused, faster unit tests.
| Annotation | Loads | Use case |
|---|---|---|
| @SpringBootTest | Full application context | End-to-end integration tests |
| @WebMvcTest | Only MVC layer (controllers, filters) | Test controllers without starting a server or database |
| @DataJpaTest | Only JPA/database layer | Test repositories; uses in-memory H2 by default |
| @DataMongoTest | Only MongoDB layer | Test MongoDB repositories |
| @RestClientTest | Only REST client components | Test HTTP Service Clients |
| @JsonTest | Only JSON serialisation components | Test Jackson serialisation/deserialisation |
| @WebFluxTest | Only WebFlux layer | Test reactive controllers |
// Integration test: full context @SpringBootTest @AutoConfigureMockMvc class OrderControllerIntegrationTest { @Autowired MockMvc mockMvc; @Autowired ObjectMapper objectMapper; @Test void createOrder_returns201() throws Exception { mockMvc.perform(post("/api/orders") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString( new CreateOrderRequest("product-1", 2)))) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id").isNotEmpty()); } } // Slice test: only MVC layer (no database) @WebMvcTest(OrderController.class) class OrderControllerTest { @Autowired MockMvc mockMvc; @MockBean OrderService service; // mock the service @Test void getOrder_returns200() throws Exception { when(service.find("O-1")).thenReturn(new OrderDto("O-1", "PENDING")); mockMvc.perform(get("/api/orders/O-1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.status").value("PENDING")); } } // Spring Boot 4: RestTestClient replaces the choice between // MockMvc and WebTestClient for most scenarios @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class OrderApiTest { @Autowired RestTestClient client; // new in Spring Boot 4 @Test void getOrders() { client.get().uri("/api/orders") .exchange() .expectStatus().isOk() .expectBodyList(OrderDto.class).hasSize(0); } }
More Related questions...