← Back to Home
Spring Boot Test
Spring Boot Test provides testing utilities and annotations to simplify unit and integration testing of Spring Boot applications. It includes support for mocking, test slices, and embedded test containers for comprehensive testing scenarios.
Key Features
Test Slices
Test only specific layers (Web, Data, Security) without loading the entire application context.
MockMvc
Test web layer without starting a full HTTP server using MockMvc for request/response testing.
TestContainers
Integration with TestContainers for testing with real databases and services in Docker containers.
Auto-configuration
Automatic configuration of test infrastructure including embedded databases and mock beans.
Use Cases
- Unit Testing: Testing individual components and services in isolation
- Integration Testing: Testing complete workflows with database and external services
- Web Layer Testing: Testing REST controllers and endpoints without HTTP server
- Repository Testing: Testing data access layer with embedded databases
- End-to-End Testing: Testing complete application flows with @SpringBootTest
Example Usage
Web layer test with MockMvc:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
Integration test with full context:
@SpringBootTest
@AutoConfigureMockMvc
class UserIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
void testCreateUser() throws Exception {
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"John\"}"))
.andExpect(status().isCreated());
}
}
Dependencies
Add the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Test Slices
Use test slices for focused testing:
@DataJpaTest // Test only JPA components
@WebMvcTest // Test only web layer
@JsonTest // Test JSON serialization
@RestClientTest // Test REST clients