Prev Next

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.

Spring Boot 4 test slice annotations
AnnotationLoadsUse case
@SpringBootTestFull application contextEnd-to-end integration tests
@WebMvcTestOnly MVC layer (controllers, filters)Test controllers without starting a server or database
@DataJpaTestOnly JPA/database layerTest repositories; uses in-memory H2 by default
@DataMongoTestOnly MongoDB layerTest MongoDB repositories
@RestClientTestOnly REST client componentsTest HTTP Service Clients
@JsonTestOnly JSON serialisation componentsTest Jackson serialisation/deserialisation
@WebFluxTestOnly WebFlux layerTest 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);
    }
}

What is the advantage of using @WebMvcTest over @SpringBootTest for controller tests?
What new test client does Spring Boot 4 introduce that replaces the choice between MockMvc and WebTestClient?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!
Acorns Logo

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Robinhood Logo

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull Logo

Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

What is Spring Boot 4 and when was it released? What is the complete modularisation of Spring Boot 4 and why does it matter? What is the Java version baseline in Spring Boot 4 and what Java features does it unlock? What is Jakarta EE 11 and what changes does it bring in Spring Boot 4? How does Spring Boot 4 auto-configuration work and what is the new @AutoConfiguration annotation? What is native API versioning in Spring Boot 4 and how do you use it? What are JSpecify nullability annotations in Spring Boot 4 and why are they important? What changed with Jackson in Spring Boot 4 and what are the migration considerations? What are @Retryable and @ConcurrencyLimit in Spring Boot 4 and how do they work? What are HTTP Service Clients in Spring Boot 4 and how do you define them? What are the key breaking changes removed in Spring Boot 4 that were deprecated in Boot 3? How does Spring Boot 4 handle dependency injection and what are the core stereotypes? What is Spring Boot's application.properties / application.yml and how does configuration work? What are Spring Boot profiles and how do you use them for environment-specific configuration? How does Spring Boot 4 testing work with @SpringBootTest and test slices? What is Spring Boot Actuator and what does it provide in Boot 4? How does Spring Boot 4 handle data access with Spring Data JPA? What is Spring Security in Spring Boot 4 and what are the key Boot 4 changes? What is the Spring Boot starter parent (POM) and how do you set up a Spring Boot 4 project? What is @SpringBootApplication and what does it combine? How do you build REST APIs with Spring Boot 4 using @RestController? How does Bean Validation work with Spring Boot 4? What is Spring Boot's embedded server and how do you configure it? What is Spring Boot's transaction management with @Transactional? What is Spring Boot's caching abstraction and how do you use it? What is Spring Boot's observability stack in Boot 4 with Micrometer and OpenTelemetry? How does Spring Boot 4 support GraalVM native images? What is Spring WebFlux and reactive programming in Spring Boot 4? What is Spring Boot's exception handling with @RestControllerAdvice? How do you use Spring Data MongoDB and other NoSQL stores in Spring Boot 4? How does Spring Boot 4 handle async processing with @Async? What is Spring Boot's externalized configuration with @Value and @ConfigurationProperties? What is Spring Boot's messaging support with Kafka in Boot 4? How do you schedule tasks in Spring Boot 4 with @Scheduled? What is Spring AI and how does it integrate with Spring Boot 4? How does Spring Boot 4 handle logging configuration? What is Spring Boot 4 migration from Boot 3: complete checklist and common pitfalls? What is Spring Boot DevTools and how does it improve development productivity? How does Spring Boot 4 support containerised deployments with Docker? What is the Spring Boot 4 vs Spring Boot 3 comparison and what are the key takeaways?
Show more question and Answers...

Hibernate

Comments & Discussions