
1. 核心依赖 (Maven)dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-test/artifactId scopetest/scope /dependency该 Starter 自动引入JUnit 5(Jupiter)MockitoAssertJSpring Test等2. 基础注解注解作用SpringBootTest启动完整 Spring 上下文集成测试Test标记测试方法BeforeEach/AfterEach每个测试前/后执行BeforeAll/AfterAll所有测试前/后执行需静态方法DisplayName给测试起中文名Disabled禁用测试3. 单元测试Service 层被测 ServiceService public class UserService { public String getUserName(Long id) { return user- id; } }测试类SpringBootTest class UserServiceTest { Autowired private UserService userService; Test DisplayName(根据ID获取用户名) void testGetUserName() { String name userService.getUserName(1L); assertEquals(user-1, name); assertNotNull(name); } }4. Web 层测试Controller使用WebMvcTest只加载 Web 层比SpringBootTest轻量。被测 ControllerRestController RequestMapping(/api/users) public class UserController { GetMapping(/{id}) public String getUser(PathVariable Long id) { return user- id; } }测试类WebMvcTest(UserController.class) class UserControllerTest { Autowired private MockMvc mockMvc; Test void testGetUser() throws Exception { mockMvc.perform(get(/api/users/1)) .andExpect(status().isOk()) .andExpect(content().string(user-1)); } }5. Mock 依赖隔离测试使用MockBean模拟 Service避免依赖真实数据库。SpringBootTest class UserControllerMockTest { Autowired private MockMvc mockMvc; MockBean private UserService userService; Test void testGetUser() throws Exception { when(userService.getUserName(1L)).thenReturn(mock-user); mockMvc.perform(get(/api/users/1)) .andExpect(status().isOk()) .andExpect(content().string(mock-user)); } }6. 数据层测试Repository使用DataJpaTest测试 JPA默认回滚事务。DataJpaTest class UserRepositoryTest { Autowired private UserRepository userRepository; Test void testSaveAndFind() { User user new User(test); userRepository.save(user); OptionalUser found userRepository.findByName(test); assertTrue(found.isPresent()); } }7. 断言进阶AssertJimport static org.assertj.core.api.Assertions.*; assertThat(user.getName()).startsWith(user); assertThat(list).hasSize(3).contains(a, b);8. 测试生命周期TestInstance(TestInstance.Lifecycle.PER_CLASS) class LifecycleTest { BeforeAll void initAll() { /* 无需 static */ } }9. 常用 Mockito 操作// 验证调用次数 verify(userService, times(1)).getUserName(anyLong()); // 抛出异常 when(userService.getUserName(1L)).thenThrow(new RuntimeException(error)); // 参数匹配 when(userService.getUserName(eq(1L))).thenReturn(user-1);10. 测试覆盖率 (Jacoco)plugin groupIdorg.jacoco/groupId artifactIdjacoco-maven-plugin/artifactId version0.8.11/version /plugin执行mvn clean test后生成target/site/jacoco/index.html。11. 最佳实践总结类型推荐注解说明单元测试ServiceSpringBootTest可配合MockBeanWeb 层测试WebMvcTest只加载 ControllerRepository 测试DataJpaTest轻量自动回滚集成测试SpringBootTest加载完整上下文测试命名should_xxx_when_xxx清晰表达意图断言AssertJ更丰富流畅12. 面试常见问题SpringBootTest和WebMvcTest区别SpringBootTest加载全部 Bean适合集成测试。WebMvcTest只加载 Web 层更快。MockBean和Mock区别MockBean是 Spring 提供的会将 Mock 对象注入 Spring 容器。Mock是 Mockito 的不管理容器。如何测试异步方法使用AsyncCountDownLatch或CompletableFuture配合await()。