SpringBoot JUnit 教程 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()。

相关新闻

最新新闻

League Akari:为英雄联盟玩家打造的终极本地化效率工具

League Akari:为英雄联盟玩家打造的终极本地化效率工具

League Akari:为英雄联盟玩家打造的终极本地化效率工具 【免费下载链接】League-Toolkit An all-in-one toolkit for LeagueClient. Gathering power 🚀. 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit 在英雄联盟的激烈对局中&am…

2026/7/6 5:29:41
Windows与Linux病毒样本提取实战指南:应急响应中的活体取证技术

Windows与Linux病毒样本提取实战指南:应急响应中的活体取证技术

1. 项目概述:为什么需要这份实战指南? 在网络安全事件频发的今天,无论是企业内网还是个人服务器,遭遇恶意软件入侵已经不是什么新鲜事。当安全告警响起,或者你发现系统出现异常进程、CPU莫名飙高、文件被加密时&#x…

2026/7/6 5:29:41
2026年5月12日更新:ChatGPT 免费用户答案中有更多图片

2026年5月12日更新:ChatGPT 免费用户答案中有更多图片

🔥个人主页:杨利杰YJlio❄️个人专栏:《Windows 疑难杂症与工单复盘案例库》 《Sysinternals实战教程》《WINDOWS教程》 《Windows PowerShell 实战》 《人工智能实战合集》《超简单:用Python让Excel飞起来》🌟 …

2026/7/6 5:29:41
AI Agent 链上操作:签名之前先生成可验证计划

AI Agent 链上操作:签名之前先生成可验证计划

AI Agent 链上操作:签名之前先生成可验证计划 一、Agent 不能直接替用户签名 AI Agent 能帮用户分析资产、构造交易、调用合约、提交治理提案。但链上操作一旦签名,就具备真实资产和权限后果。让 Agent 直接决定并发起签名,是非常危险的设计。…

2026/7/6 5:29:41
League Akari:如何5分钟掌握英雄联盟终极自动化工具箱

League Akari:如何5分钟掌握英雄联盟终极自动化工具箱

League Akari:如何5分钟掌握英雄联盟终极自动化工具箱 【免费下载链接】League-Toolkit An all-in-one toolkit for LeagueClient. Gathering power 🚀. 项目地址: https://gitcode.com/gh_mirrors/le/League-Toolkit League Akari 是一款基于官方…

2026/7/6 5:29:41
如何轻松管理空洞骑士模组:Scarab模组管理器完全指南

如何轻松管理空洞骑士模组:Scarab模组管理器完全指南

如何轻松管理空洞骑士模组:Scarab模组管理器完全指南 【免费下载链接】Scarab An installer for Hollow Knight mods written with Avalonia. 项目地址: https://gitcode.com/gh_mirrors/sc/Scarab 你是否曾经因为空洞骑士模组安装太复杂而感到困扰&#xff…

2026/7/6 5:24:40

月新闻