SpringBoot 从 2.4.X 开始默认使用 JUnit5 做单元测试

导入依赖

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

注解说明

注解

使用位置

说明

@SpringBootTest

标注类

启用 SpringBoot 作为测试核心(可以使用Spring的功能)

@Test

标注方法

表示要测试的方法

@DisplayName

标注类

为此测试类命名

@BeforeEach

标注方法

在每个单元测试之前执行

@AfterEach

标注方法

在每个单元测试之后执行

@BeforeAll

标注方法

在所有单元测试之前执行(标注静态方法)

@AfterAll

标注方法

在所有单元测试之后执行(标注静态方法)

@Disabled

标注类或方法

禁用此类或方法

@Timeout

标注方法

设置此方法执行超时时间

@RepeatedTest

标注方法

重复执行次数

@ParameterizedTest

标注方法

参数化测试

@ValueSource

标注方法

参数化测试 提供一个包含值的入参

@NullSource

标注方法

参数化测试 提供一个 null 的入参

@EnumSource

标注方法

参数化测试 提供一个枚举入参

@CsvFileSource

标注方法

参数化测试 提供一个 csv 文件入参

@MethodSource

标注方法

参数化测试 提供一个方法的返回值入参(方法返回值必须为 Stream<T> )

@Tag

标注类或方法

测试类别 需搭配 maven 插件使用

@ExtendWith

标注类或方法

为测试类或方法提供扩展类引用

使用 @SpringBootTest @Test @DisplayName

junit 测试springboot dao_spring boot

使用 @BeforeAll 在 Spring 之前执行

junit 测试springboot dao_maven_02


junit 测试springboot dao_参数化_03

使用 @BeforeEach @AfterEach 在 test 方法前后执行

junit 测试springboot dao_参数化_04

使用 @AfterAll 所有方法全完成 Spring 关闭之前执行

junit 测试springboot dao_junit5_05

使用 @Disabled

junit 测试springboot dao_spring boot_06


junit 测试springboot dao_参数化_07

使用 @Timeout

junit 测试springboot dao_maven_08

使用 @RepeatedTest

junit 测试springboot dao_junit5_09

使用 @ParameterizedTest

使用 @ValueSource

junit 测试springboot dao_junit5_10

使用 @NullSource

junit 测试springboot dao_单元测试_11

使用 @EnumSource

junit 测试springboot dao_参数化_12

使用 @MethodSource

junit 测试springboot dao_参数化_13

使用 @Tag 此注解需搭配 maven 插件使用

<!-- 单元测试使用 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                	<!-- 解决运行乱码问题 -->
                	<argLine>-Dfile.encoding=UTF-8</argLine>
                    <!-- include tags -->
                    <groups>dev, local, prod</groups>
                    <!-- exclude tags -->
                    <excludedGroups>exclude</excludedGroups>
                </configuration>
            </plugin>

junit 测试springboot dao_spring boot_14


引入 local 标签排除 exclude 标签

junit 测试springboot dao_单元测试_15

junit 测试springboot dao_spring boot_16

使用 @ExtendWith 参考 @SpringBootTest 注解源码

junit 测试springboot dao_单元测试_17

断言说明

方法

说明

assertEquals

判断两个对象或两个原始类型是否相等

assertNotEquals

判断两个对象或两个原始类型是否不相等

assertSame

判断两个对象引用是否指向同一个对象

assertNotSame

判断两个对象引用是否指向不同的对象

assertTrue

判断给定的布尔值是否为 true

assertFalse

判断给定的布尔值是否为 false

assertNull

判断给定的对象引用是否为 null

assertNotNull

判断给定的对象引用是否不为 null

测试 assertEquals assertNotEquals

junit 测试springboot dao_junit5_18

测试 assertSame assertNotSame

junit 测试springboot dao_单元测试_19

测试 assertTrue assertFalse

junit 测试springboot dao_maven_20

测试 assertNull assertNotNull

junit 测试springboot dao_spring boot_21