解决 IntelliJ IDEA 低版本与 Spring Boot 2.2+ 应用 JUnit 5 的兼容性问题的三种思路:降级 IntelliJ IDEA 版本、应用 JUnit 4 进行单元测试、升高 Spring Boot 版本

在应用 Spring Boot 2.2 版本以上时,默认应用 JUnit 5 进行测试。然而,如果您的 IntelliJ IDEA 版本低于 2017.3,可能会遇到以下错误信息:

正告: TestEngine with ID 'junit-jupiter' failed to discover testsjava.lang.AbstractMethodError: Method org/junit/platform/launcher/core/DefaultDiscoveryRequest.getFiltersByType(Ljava/lang/Class;)Ljava/util/List; is abstract...Empty test suite.

解决思路有三个:

  1. 降级 IntelliJ IDEA 版本:JUnit 5 与 IntelliJ IDEA 2017.3 版本及更高版本兼容。倡议降级到最新版本的 IntelliJ IDEA,以取得对 JUnit 5 的齐全反对。新版本的 IntelliJ IDEA 提供了更好的集成和反对,可能更轻松地编写和运行 JUnit 5 测试。倡议拜访 IntelliJ IDEA 的官方网站,下载并装置最新版本的 IntelliJ IDEA。
  2. 如果因其余起因不想降级IntelliJ IDEA 版本,同时Spring Boot的版本也不调整,也能够应用 JUnit 4 进行单元测试:须要在 pom.xml 文件中做如下调整:
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-test</artifactId>    <scope>test</scope>    <exclusions>        <exclusion>            <groupId>org.junit.jupiter</groupId>            <artifactId>junit-jupiter-api</artifactId>        </exclusion>    </exclusions></dependency><dependency>    <groupId>junit</groupId>    <artifactId>junit</artifactId>    <version>4.13.2</version>    <scope>test</scope></dependency>

测试类示例:

@RunWith(SpringRunner.class)@SpringBootTestpublic class Demo0611ApplicationTests {    @Test    public void contextLoads() {        // Your test logic here    }}

通过以上调整,您能够应用 JUnit 4 进行单元测试。

  1. 如果不想降级IntelliJ IDEA 版本,也不想调整pom文件,则只有升高 Spring Boot 版本:如将 Spring Boot 版本退回到 2.2 以下,例如 2.1.3.RELEASE,这样默认就会应用 JUnit 4 进行测试,而不是 JUnit 5。

以上是解决 IntelliJ IDEA 低版本与 Spring Boot 2.2+ 应用 JUnit 5 的兼容性问题的三种思路。大家能够依据理论状况抉择适宜的解决方案。

本文由mdnice多平台公布