一、JUnit5理论
1.Junit5介绍
Junit5由以下3部分组成:
- JUnit Platform是基于JVM的运行测试的基础框架在,它定义了开发运行在这个测试框架上的TestEngine API。此外该平台提供了一个控制台启动器,可以从命令行启动平台,可以为Gradle和 Maven构建插件,同时提供基于JUnit 4的Runner。
- JUnit Jupiter是在JUnit 5中编写测试和扩展的新编程模型和扩展模型的组合.Jupiter子项目提供了一个TestEngine在平台上运行基于Jupiter的测试。
- JUnit Vintage提供了一个TestEngine在平台上运行基于JUnit 3和JUnit 4的测试。
2.常用注解
3.断言方法
常用断言 Assertions
- assertEquals 断言预期值和实际值相等
- assertAll 分组断言,执行其中包含的所有断言
- assertArrayEquals 断言预期数组和实际数组相等
- assertFalse 断言条件为假
- assertNotNull 断言不为空
- assertSame 断言两个对象相等
- assertTimeout 断言超时
- fail 使单元测试失败
二、JUnit5结合Springboot实践
1.pom依赖
采用Springboot2.7.x 版本结合Junit进行验证,在这个版本中默认依赖的就是Junit5。添加pom依赖时将junit-vintage-engine加入到exclusion中,是为了排除Junit4 API被误引入。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2.IDEA中自动生成单元测试
在IDEA中右键方法,选择Generate选项,即可自动生成单元测试类和方法。
3.测试类中注解的使用
针对Junit5,只需要加上注解:@SpringBootTest,他的作用是加载ApplicationContext容器。
@SpringBootTest
注意:如果使用的是Junit4,则还需要加上注解:@RunWith(SpringRunner.class),他的作用是启动测试器,保障Junit4的@Test注解能在ApplicationContext容器中生效。
@RunWith(SpringRunner.class)
参考资料
- 单元测试 - Junit5 详解:https://www.pdai.tech/md/develop/ut/dev-ut-x-junit5.html
- 【SpringBoot深入浅出系列】SpringBoot之集成JUnit5进行单元测试:https://bbs.huaweicloud.com/blogs/349189
- Spring Boot 集成 JUnit5,更优雅单元测试!:https://cloud.tencent.com/developer/article/2271888?areaSource=&traceId=
- Junit5 官网:https://junit.org/junit5/?spm=a2c6h.12873639.article-detail.5.3f0c1fdajVdpUK
- Springboot 单元测试 @SpringBootTest 与 RunWith:https://blog.csdn.net/howeres/article/details/108339464 (重点讲了@SpringBootTest和@RunWith 区别)