目录
第十章 单元测试JUnit5
10.1 JUnit5的变化
SpringBoot2.2.0版本开始引入JUnit 5作为单元测试默认库。作为最新版本的JUnit框架,JUnit5与之前版本的Junit框架有很大的不同,由三个不同子项目的几个不同模块组成。
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
-
JUnit Platform:Junit Platform是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。
-
JUnit Jupiter:JUnit Jupiter提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部包含了一个测试引擎,用于在Junit Platform上运行。
-
JUnit Vintage:由于JUint已经发展多年,为了照顾老的项目,JUnit Vintage提供了兼容JUnit4.x、Junit3.x的测试引擎。
注意:SpringBoot2.4以上版本移除了默认对Vintage的依赖(不能使用junit4的功能@Test)。如果需要兼容junit4需要自行引入
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
现在版本的使用:
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
@SpringBootTest
class Boot05WebAdminApplicationTests {
@Test
void contextLoads() {
}
}
以前的使用:@SpringBootTest + @RunWith(SpringTest.class)
SpringBoot整合Junit以后:
- 编写测试方法:@Test标注(注意需要使用junit5版本的注解)
- Junit类具有Spring的功能,如@Autowired、@Transactional标注测试方法,测试完成后自动回滚
10.2 JUnit5常用注解
JUnit5的注解与JUnit4的注解有所变化
- @Test:表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一,不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
- @ParameterizedTest:表示方法是参数化测试,下方会有详细介绍
- @RepeatedTest:表示方法可重复执行,下方会有详细介绍
- @