You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Maven 3.8.6无法运行JUnit5测试用例的求助

问题描述

测试类路径:module > src > test > java > TestRunner.java

为排查问题,我同时写了TestNG测试和JUnit5测试,但只有TestNG测试能正常执行,执行命令是:

mvn test -Dtest=TestRunner

我查了相关资料后,尝试用surefire 2.22.0版本,并在插件里指定了junit-jupiter-engine依赖,但问题还是没解决。另外,mvn dependency:tree输出里没有JUnit4的依赖。

当前插件配置如下,求解决办法:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.8.2</version>
        </dependency>
    </dependencies>
</plugin>
解决建议
  • 升级surefire插件版本
    surefire 2.22.0对JUnit5的支持不够完善,建议直接升级到3.0.0-M7及以上版本,新版本能自动识别JUnit5依赖,不需要在插件内部手动配置junit-jupiter-engine。

  • 明确指定双测试引擎(不升级插件的情况下)
    如果不想升级插件,在现有配置里添加configuration节点,同时指定JUnit5和TestNG的测试提供者:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.6.1</version> <!-- 替换成你项目实际使用的TestNG版本 -->
        </dependency>
    </dependencies>
    <configuration>
        <providers>
            <provider>org.apache.maven.surefire.junitplatform.JUnitPlatformProvider</provider>
            <provider>org.apache.maven.surefire.testng.TestNGProvider</provider>
        </providers>
    </configuration>
</plugin>
  • 检查JUnit5依赖是否完整
    确保项目的dependencies节点里已经完整引入JUnit5的API和引擎依赖:
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>
  • 核对测试类注解
    确认JUnit5测试类用的是@org.junit.jupiter.api.Test注解,别不小心用成JUnit4的@org.junit.Test,注解错了会导致surefire识别不到。

  • 执行时强制启用JUnit5
    如果临时想执行JUnit5测试,可以在命令里加上参数:

mvn test -Dtest=TestRunner -Dsurefire.junit.jupiter.enabled=true

内容的提问来源于stack exchange,提问作者xploreraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 06:52:26