[兼容JUnit 5]使用带有Spring Boot 2.2、2.3的JUnit 5编写测试


本文介绍"与JUnit5兼容的Spring boot 2.2或更高版本"。
我希望它将对以下目的有用!

  • 从Spring Boot 2.1或更低版本更新到2.2或更高版本
  • 从JUnit 4转移到JUnit 5
  • 我想在编写JUnit5时预先排除JUnit4
  • 0.假设

    环境

    • Java 8?(Spring Boot 2.2及更高版本支持Java 8和11)
    • Spring Boot 2.2?

    要知道的好知识

    • Spring Boot 2.2及更高版本中的默认值为JUnit 5
    • JUnit4和JUnit5基本不兼容
    • 目前,JUnit 4和5可以共存(最终会消失)

    1.使用JUnit 5

    的依赖项

    • 要做的事情

      • 排除junit-vintage-engine(由于使JUnit4起作用的依赖项)

    例子1.对于Maven

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <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.对于Gradle

    1
    2
    3
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }

    2.更正了有关JUnit4

    的描述

    • @RunWith已过时

      • 对应...删除或更改为@ExtendWith
    • @Test的导入源已更改

      • 在对应之前... import org.junit.Test;

      • 对应之后... import org.junit.jupiter.api.Test;

    • @Before已过时

      • 对应...更改为@BeforeEach@BeforeAll

    (参考)

    ↓这是参考站点
    --Spring Boot 2.2发行说明·spring-projects / spring-boot Wiki·GitHub
    -《 JUnit 5用户指南》