What is Spring Boot testing with @SpringBootTest?
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.