springboot中的怎么用JUnit进行测试的?

在 Spring Boot 中使用 JUnit 进行单元测试非常简单,官方已帮你集成好 JUnit5(Spring Boot 2.x 默认),只需 3 步即可跑起来。下面给出一份「最小可运行」示例,并补充常见场景(Mock、Web、事务)的写法,复制即可用。

1.引入依赖(已自带,确认即可)

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

该包已包含 JUnit5、Mockito、AssertJ、Hamcrest 等,无需额外导包

2.最简单的 service 层单元测试

java 复制代码
@SpringBootTest                      // 1. 拉起整个 Spring 容器
class UserServiceTest {

    @Autowired
    private UserService userService;   // 2. 直接注入真实 Bean

    @Test                              // 3. JUnit5 注解
    void getUserById() {
        User u = userService.getById(1L);
        assertThat(u.getName()).isEqualTo("Jack");   // AssertJ 流式断言
    }
}

运行:IDEA 在方法左侧点击 ▶ 即可,首次会自动编译并启动容器,完成后看到绿色条即通过

3.常见场景快速模板

|--------------------|----------------------------------------------------------------------|
| 场景 | 关键注解/工具 |
| ① 不启动服务器,只测 web 切片 | @WebMvcTest(YourController.class) + MockMvc |
| ② 快速 Mock 依赖 | @MockBean |
| ③ 测试持久层 | @DataJpaTest + @AutoConfigureTestDatabase(replace=ANY) |
| ④ 事务回滚 | @Transactional(默认回滚) |
| ⑤ 随机端口 HTTP 测试 | @SpringBootTest(webEnvironment = RANDOM_PORT) + TestRestTemplate |

4.JUnit4 → JUnit5 对照(老项目迁移)

| JUnit4 | JUnit5 |

|---|---|

| @RunWith(SpringRunner.class) | 不需要,或改为 @ExtendWith(SpringExtension.class) |

| @Test(org.junit.Test) | @Test(org.junit.jupiter.api.Test) |

| Assert.assertEquals | Assertions.assertEqualsassertThat(...).isEqualTo(...) |

5.一键生成测试类小技巧

在 IDEA 里把光标停在要测试的类名上 → Ctrl+Shift+T → Create New Test → 选择 JUnit5,IDE 会自动在 src/test/java 对应包下生成模板,再补 @SpringBootTest 即可

6.运行与查看报告

  • 命令行:mvn test

  • 报告:target/surefire-reports/index.html(Maven)

  • 覆盖率:加 jacoco-maven-plugin 后执行 mvn test jacoco:report,打开 target/site/jacoco/index.html 即可看到行/分支覆盖率

照着以上模板,10 分钟即可把 Spring Boot 项目的单元测试跑起来;后续再按需拆分层级测试(@WebMvcTest、@DataJpaTest 等)即可。祝编码愉快!

相关推荐
金銀銅鐵2 天前
浅解 JUnit 4 第十一篇:@Before 注解和 @After 注解如何发挥作用?
junit·单元测试
金銀銅鐵3 天前
浅解 JUnit 4 第十篇:方法上的 @Ignore 注解
junit·单元测试
金銀銅鐵7 天前
浅解 JUnit 4 第九篇:JUnitCore (下)
junit·单元测试
钟智强7 天前
CVE-2025-49844高危预警:Redis Lua脚本引擎UAF漏洞深度剖析与POC实战
数据库·redis·web安全·junit·lua
开开心心就好7 天前
内存清理软件灵活设置,自动阈值快捷键清
运维·服务器·windows·pdf·harmonyos·risc-v·1024程序员节
金銀銅鐵8 天前
浅解 JUnit 4 第八篇:JUnitCore (上)
junit·单元测试
学传打活9 天前
【边打字.边学昆仑正义文化】_5_宇宙物种创造简史(1)
微信公众平台·1024程序员节·汉字·昆伦正义文化
xcLeigh10 天前
打破机房围墙:VMware+cpolar构建跨网络虚拟实验室
vmware·内网穿透·cpolar·实验室·远程访问·1024程序员节
百锦再10 天前
Java中的日期时间API详解:从Date、Calendar到现代时间体系
java·开发语言·spring boot·struts·spring cloud·junit·kafka