解决 IntelliJ IDEA 低版本与 Spring Boot 2.2+ 的测试兼容性问题

解决 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 tests
java.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)
@SpringBootTest
public 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 的兼容性问题的三种思路。大家可以根据实际情况选择适合的解决方案。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容