JUnit5 学习之一:基本操作 - 今日头条

本文由 简悦 SimpRead 转码, 原文地址 www.toutiao.com

欢迎访问我的 GitHubhttps://github.

https://github.com/zq2599/blog_demos

内容:所有原创文章分类和汇总,及配套源码,涉及 Java、Docker、Kubernetes、DevOPS 等;

《JUnit5 学习》系列旨在通过一系列知识归纳和实战,具备在 SpringBoot 环境下开发和执行单元测试的能力;

本文是《JUnit5 学习》系列的第一篇,通过实战学习在 SpringBoot 框架下 JUnit5 的基本功能,全篇章节如下:

  1. JUnit5 简介
  2. SpringBoot 对 Junit5 的依赖
  3. 常用注解简介
  4. 5 版本已废弃的注解
  5. 进入实战环节,先介绍版本和环境信息
  6. 创建《JUnit5 学习》系列源码的父工程
  7. 创建子工程,编码体验常用注解
  • JUnit 是常用的 java 单元测试框架,5 是当前最新版本,其整体架构如下 (图片来自网络):

https://p26.toutiaoimg.com/origin/pgc-image/9ef69489eab14f5bb03c36b74aa0fc5e?from=pc

  • 从上图可见,整个 Junit5 可以划分成三层:顶层框架 (Framework)、中间的引擎(Engine),底层的平台(Platform);
  • 官方定义 Junit5 由三部分组成:Platform、Jupiter、Vintage,功能如下;
  • Platform:位于架构的最底层,是 JVM 上执行单元测试的基础平台,还对接了各种 IDE(例如 IDEA、eclipse),并且还与引擎层对接,定义了引擎层对接的 API;
  • Jupiter:位于引擎层,支持 5 版本的编程模型、扩展模型;
  • Vintage:位于引擎层,用于执行低版本的测试用例;
  • 可见整个 Junit Platform 是开放的,通过引擎 API 各种测试框架都可以接入;
  • 这里使用 SpringBoot 版本为 2.3.4.RELEASE,在项目的 pom.xml 中依赖 Junit5 的方法如下:
1
2
3
4
5
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  • 如下图红框,可见 Junit5 的 jar 都被 spring-boot-starter-test 间接依赖进来了:

https://p26.toutiaoimg.com/origin/pgc-image/6ea1896e9bb54bf9af351bb55e15d56b?from=pc

  • 在使用 Junit4 的时候,咱们经常这么写单元测试类:
1
2
3
@RunWith(SpringRunner.class)
@SpringBootTest
public class XXXTest {
  • 对于上面的 RunWith 注解,Junit5 官方文档的说法如下图红框所示,已经被 ExtendWith 取代:

https://p26.toutiaoimg.com/origin/pgc-image/6170317ce26a4f1d9a8a1cf0a6ce3672?from=pc

  • 咱们再来看看 SpringBootTest 注解,如下图,可见已经包含了 ExtendWith

https://p26.toutiaoimg.com/origin/pgc-image/bd69f1ce90be412a92a9324079edf940?from=pc

  • 综上所述,SpringBoot+Junit5 时,RunWith 注解已经不需要了,正常情况下仅 SpringBootTest 注解即可,如果对扩展性有更多需求,可以添加 ExtendWith 注解,如下图:

https://p26.toutiaoimg.com/origin/pgc-image/080b94063d3544d08b89250bf9e0db88?from=pc

注意,接下来提到的测试方法,是指当前 class 中所有被 @Test、@RepeatedTest、@ParameterizedTest、@TestFactory 修饰的方法;

  1. ExtendWith:这是用来取代旧版本中的 RunWith 注解,不过在 SpringBoot 环境如果没有特别要求无需额外配置,因为 SpringBootTest 中已经有了;
  2. Test:被该注解修饰的就是测试方法;
  3. BeforeAll:被该注解修饰的必须是静态方法,会在所有测试方法之前执行,会被子类继承,取代低版本的 BeforeClass;
  4. AfterAll:被该注解修饰的必须是静态方法,会在所有测试方法执行之后才被执行,会被子类继承,取代低版本的 AfterClass;
  5. BeforeEach:被该注解修饰的方法会在每个测试方法执行前被执行一次,会被子类继承,取代低版本的 Before;
  6. AfterEach:被该注解修饰的方法会在每个测试方法执行后被执行一次,会被子类继承,取代低版本的 Before;
  7. DisplayName:测试方法的展现名称,在测试框架中展示,支持 emoji;
  8. Timeout:超时时长,被修饰的方法如果超时则会导致测试不通过;
  9. Disabled:不执行的测试方法;

以下的注解都是在 5 之前的版本使用的,现在已经被废弃:

https://p26.toutiaoimg.com/origin/pgc-image/de92137d1b584d7a9889af80bb130ee2?from=pc

整个系列的编码和执行在以下环境进行,供您参考:

  1. 硬件配置:处理器 i5-8400,内存 32G,硬盘 128G SSD + 500G HDD
  2. 操作系统:Windows10 家庭中文版
  3. IDEA:2020.2.2 (Ultimate Edition)
  4. JDK:1.8.0_181
  5. SpringBoot:2.3.4.RELEASE
  6. JUnit Jupiter:5.6.2
  • 接下来开始实战,咱们先建好 SpringBoot 项目;

为了简化代码,项目中使用了 lombok,请您在 IDEA 中安装 lombok 插件;

如果您不想编码,可以在 GitHub 下载所有源码,地址和链接信息如下表所示 (

https://github.com/zq2599/blog_demos):

https://p26.toutiaoimg.com/origin/pgc-image/5b88b2760adb4532b2f8452061b7a671?from=pc

  • 这个 git 项目中有多个文件夹,本章的应用在 junitpractice 文件夹下,如下图红框所示:

https://p26.toutiaoimg.com/origin/pgc-image/c5f29e392f794c4a9a599c0855f75cbe?from=pc

  • junitpractice 是父子结构的工程,本篇的代码在 junit5experience 子工程中,如下图:

https://p26.toutiaoimg.com/origin/pgc-image/f90708ce52ec405eab2809f6af0b3045?from=pc

  • 为了便于管理整个系列的源码,在此建立名为 junitpractice 的 maven 工程,后续所有实战的源码都作为 junitpractice 的子工程;
  • junitpractice 的 pom.xml 如下,可见是以 SpringBoot 的 2.3.4.RELEASE 版本作为其父工程:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <modules>
        <module>simplebean</module>
        <!--
        <module>testenvironment</module>
        -->
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>junitpractice</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.16</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

接下来咱们准备一个简单的 SpringBoot 工程用于做单元测试,该工程有 service 和 controller 层,包含一些简单的接口和类;

  • 创建名为 junit5experience 的子工程,pom.xml 如下,注意单元测试要依赖 spring-boot-starter-test:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.bolingcavalry</groupId>
        <artifactId>junitpractice</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <groupId>com.bolingcavalry</groupId>
    <artifactId>junit5experience</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>junit5experience</name>
    <description>Demo project for simplebean in Spring Boot junit5</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  • 写一些最简单的业务代码,首先是 service 层的接口 HelloService.java:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package com.bolingcavalry.junit5experience.service;

public interface HelloService {
    String hello(String name);
    int increase(int value);
    /**
     * 该方法会等待1秒后返回true,这是在模拟一个耗时的远程调用
     * @return
     */
    boolean remoteRequest();
}
  • 上述接口对应的实现类如下,hello 和 increase 方法分别返回 String 型和 int 型,remoteRequest 故意 sleep 了 1 秒钟,用来测试 Timeout 注解的效果:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.bolingcavalry.junit5experience.service.impl;

import com.bolingcavalry.junit5experience.service.HelloService;
import org.springframework.stereotype.Service;

@Service()
public class HelloServiceImpl implements HelloService {
    @Override
    public String hello(String name) {
        return "Hello " + name;
    }

    @Override
    public int increase(int value) {
        return value + 1;
    }

    @Override
    public boolean remoteRequest() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }

        return true;
    }
}
  • 添加一个简单的 controller:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package com.bolingcavalry.junit5experience.controller;

import com.bolingcavalry.junit5experience.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public String hello(@PathVariable String name){
        return helloService.hello(name);
    }
}
  • 启动类:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.bolingcavalry.junit5experience;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Junit5ExperienceApplication {

    public static void main(String[] args) {
        SpringApplication.run(Junit5ExperienceApplication.class, args);
    }
}
  • 以上就是一个典型的 web 工程,接下来一起为该工程编写单元测试用例;
  • 在下图红框位置新增单元测试类:

https://p26.toutiaoimg.com/origin/pgc-image/93023dc969b5456a8fcfe00cab5640a1?from=pc

  • 测试类的内容如下,涵盖了刚才提到的常用注解,请注意每个方法的注释说明:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.bolingcavalry.junit5experience.service.impl;

import com.bolingcavalry.junit5experience.service.HelloService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
@Slf4j
class HelloServiceImplTest {

    private static final String NAME = "Tom";

    @Autowired
    HelloService helloService;

    /**
     * 在所有测试方法执行前被执行
     */
    @BeforeAll
    static void beforeAll() {
        log.info("execute beforeAll");
    }

    /**
     * 在所有测试方法执行后被执行
     */
    @AfterAll
    static void afterAll() {
        log.info("execute afterAll");
    }

    /**
     * 每个测试方法执行前都会执行一次
     */
    @BeforeEach
    void beforeEach() {
        log.info("execute beforeEach");
    }

    /**
     * 每个测试方法执行后都会执行一次
     */
    @AfterEach
    void afterEach() {
        log.info("execute afterEach");
    }

    @Test
    @DisplayName("测试service层的hello方法")
    void hello() {
        log.info("execute hello");
        assertThat(helloService.hello(NAME)).isEqualTo("Hello " + NAME);
    }

    /**
     * DisplayName中带有emoji,在测试框架中能够展示
     */
    @Test
    @DisplayName("测试service层的increase方法\uD83D\uDE31")
    void increase() {
        log.info("execute increase");
        assertThat(helloService.increase(1)).isEqualByComparingTo(2);
    }

    /**
     * 不会被执行的测试方法
     */
    @Test
    @Disabled
    void neverExecute() {
        log.info("execute neverExecute");
    }

    /**
     * 调用一个耗时1秒的方法,用Timeout设置超时时间是500毫秒,
     * 因此该用例会测试失败
     */
    @Test
    @Timeout(unit = TimeUnit.MILLISECONDS, value = 500)
    @Disabled
    void remoteRequest() {
        assertThat(helloService.remoteRequest()).isEqualTo(true);
    }
}
  • 接下来执行测试用例试试,点击下图红框中的按钮:

https://p26.toutiaoimg.com/origin/pgc-image/03d0f768c8f744818e71bd3dfa7eb1b2?from=pc

  • 如下图,在弹出的菜单中,点击红框位置:

https://p26.toutiaoimg.com/origin/pgc-image/80b3a69d39fa4badb2cf143fe8f6377d?from=pc

  • 执行结果如下,可见 Displayname 注解的值作为测试结果的方法名展示,超时的方法会被判定为测试不通过Disable 注解修饰的方法则被标记为跳过不执行

https://p26.toutiaoimg.com/origin/pgc-image/976d6729d45542748e10bf0cba92756f?from=pc

  • 在父工程 junitpractice 的 pom.xml 文件所在目录,执行 mvn test 命令,可以看到 maven 执行单元测试的效果:

https://p26.toutiaoimg.com/origin/pgc-image/2fb5e867f4464cfcb58fd5a67943d06f?from=pc

  • 至此,咱们对 SpringBoot 环境下的 Junit5 有了最基本的了解,接下来的章节会展开更多知识点和细节,对单元测试做更深入的学习。

https://p26.toutiaoimg.com/origin/dfic-imagehandler/1e54eebe-5e63-424d-b320-7e5eb09fd02e?from=pc