Springboot 2.x 单元测试 JUnit 5

一、JUnit5 简介

Spring Boot 2.2.0 版本开始引入 JUnit5 作为单元测试默认库, JUnit5作为最新版本的 JUnit框架, 它与之前版本的 JUnit框架有很大的不同,由三个不同子项目的几个不同模块组成.

JUnit5 = JUnitPlatform + JUnitJupiter + JUnitVintage

JUnitPlatform: JUnitPlatform 是在 JVM 上启动测试框架的基础,不仅支持 JUnit自制的测试引擎,其它测试引擎也都可以接入.

JUnitJupiter: JUnitJupiter 提供了JUnit5 的新的编程模型,是 JUnit5 新特性的核心.内部包含了一个测试引擎,用于在 JUnitPlatform 上运行.

JUnitVintage: 由于 JUnit已经发展多年,为了照顾老的项目,JUnitVintage 提供了兼容 JUnit 4.x,JUnit 3.x 的测试引擎.

注意:
SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖.如果需要兼容 JUnit4.x 版本,需要自行引入(不能使用junit4的功能 @Test)

打开项目发布信息 ----> 选择 v 2.4 这个版本

该版本的变更中说明了已经移除了 JUnit5 了

 

二、整合 JUnit5 

未整合 JUnit 之前

@SpringBootTest + @RunWith(SpringTest.class)

Springboot 整合 Junit 以后
编写测试方法:@Test标注(注意需要使用 junit5 版本的注解)
Junit类具有 Spring 的功能, 例如 @Autowired、@Transactional (标注测试方法,测试完成后自动回)

我们只需要引入 spring-boot-starter-test 依赖即可完成整合,其它的 Springboot 底层都已经帮我们自动配置好了

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

  

三、Junit 5 常用注解

具体的使用规范可以参考官网 JUnit 5 官网 https://junit.org/junit5/

JUnit5 的注解与JUnit4 的注解有所变化,具体可以参考官方文档 https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

注解 说明
@Test 表示方法是测试方法,但是与 JUnit4 的 @Test 不同,它的职责非常单一不能声明任何属性,拓展的测试将会由 Jupiter 提供额外测试
@DisplayName 为测试类或者测试方法设置展示名称
@BeforeAll 表示在所有单元测试之前执行
@BeforeEach 表示在每个单元测试之前执行
@Timeout 表示测试方法运行如果超过了指定时间将会返回错误
@Disabled 表示测试类或测试方法不执行
@RepeatedTest 表示方法可重复执行
@ExtendWith 为测试类或测试方法提供扩展类引用
@AfterEach 表示在每个单元测试之后执行
@AfterAll 表示在所有单元测试之后执行

 

 

 

 

 

 

 

 

 

 

 

 

 

我们就选取几个测试注解来使用一下

1、测试类

@DisplayName("测试类")
@SpringBootTest
class DatasourceApplicationTests {

    @Test
    @BeforeAll
    public static void beforeAll() {
        System.out.println("@BeforeAll: 表示在所有单元测试之前执行");
    }

    @BeforeEach
    public void beforeEach() {
        System.out.println("@BeforeEach: 表示在每个单元测试之前执行");
    }

    @Test
    @DisplayName("测试方法一")
    public void test01() {
        System.out.println("@DisplayName: 为测试类或者测试方法设置展示名称");
    }

    @Test
    @DisplayName("测试方法二")
    @Timeout(value=1,unit=TimeUnit.MICROSECONDS)
    public void test02() {
        System.out.println("@Timeout: 表示测试方法运行如果超过了指定时间将会返回错误");
    }
}

2、测试结果

 

当然 JUnit 5还有很多其它的使用,例如:断言、前置条件、嵌套测试、参数化测试 以及如何从 Junit 4 迁移到  JUnit 5 等等

在实际开发过程中,建议去参照官方文档的用户指南并且结合自身项目的实际情况选择合适的 JUnit 5 功能

 

posted @ 2021-01-21 14:30  变体精灵  阅读(4985)  评论(0编辑  收藏  举报