What is Spring Boot testing with @SpringBootTest?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Spring Boot development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Spring Boot provides comprehensive testing support. Key annotations: @SpringBootTest: loads the full application context — integration tests. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") class UserControllerIntegrationTest { @Autowired private TestRestTemplate restTemplate; @Test void shouldCreateUser() { CreateUserRequest req = new CreateUserRequest("Alice", "alice@example.com"); ResponseEntity<User> resp = restTemplate.postForEntity("/api/users", req, User.class); assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.CREATED); assertThat(resp.getBody().getEmail()).isEqualTo("alice@example.com"); } }. @WebMvcTest: loads only MVC layer (controller, filters, security — no services or repositories). Faster than @SpringBootTest. Mock services: @WebMvcTest(UserController.class) class UserControllerTest { @Autowired MockMvc mockMvc; @MockBean UserService userService; @Test void shouldReturnUsers() throws Exception { when(userService.findAll()).thenReturn(List.of(new User("Alice"))); mockMvc.perform(get("/api/users")).andExpect(status().isOk()).andExpect(jsonPath("$[0].name").value("Alice")); } }. @DataJpaTest: loads only JPA layer (repositories, entities). Uses in-memory H2 by default. @MockBean: creates a Mockito mock and registers it in the Spring context. @SpyBean: wraps a real Spring bean with Mockito spy. AssertJ for fluent assertions. Testcontainers for integration tests with real databases.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Spring Boot answers easy to follow.