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

Spring Boot项目执行mvn test时Maven无法识别TestNG测试的问题求助

Maven无法识别TestNG测试用例的解决方案

从你的日志里能看到关键线索:Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider——Maven的Surefire插件自动选择了JUnit Platform的执行器,而非TestNG的,这就是IDEA能正常运行测试但Maven找不到测试用例的核心原因。结合你的配置,给你几个可行的解决方案:

方案1:强制Surefire使用TestNG Provider

在maven-surefire-plugin中添加TestNG Provider依赖,明确指定使用TestNG的执行逻辑:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${maven-surefire-plugin.version}</version>
    <configuration>
        <systemPropertyVariables>
            <webdriver.chrome.driver>/tmp/chromedriver/chromedriver</webdriver.chrome.driver>
        </systemPropertyVariables>
        <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
        </suiteXmlFiles>
    </configuration>
    <!-- 添加TestNG Provider依赖,强制指定执行器 -->
    <dependencies>
        <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>surefire-testng</artifactId>
            <version>${maven-surefire-plugin.version}</version>
        </dependency>
    </dependencies>
</plugin>

方案2:排除Spring Boot Test中的JUnit依赖

spring-boot-starter-test默认包含了JUnit 5的相关依赖,这些依赖会干扰Surefire对TestNG的识别。你可以在依赖中排除JUnit相关组件:

<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>
        <exclusion>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>

排除后,Surefire会自动检测到TestNG的存在并切换到对应的执行器。

方案3:确保testng.xml路径正确

检查你的testng.xml文件位置:

  • 如果放在项目根目录(和pom.xml同层级),当前配置无需修改;
  • 如果放在src/test/resources下,需要修改suiteXmlFile的路径:
    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
    
    或者用classpath引用更稳妥:
    <suiteXmlFile>classpath:testng.xml</suiteXmlFile>
    

方案4:升级Surefire插件版本

你当前使用的maven-surefire-plugin:3.0.0-M6是较老的预览版本,升级到最新稳定版(比如3.2.5)可以提升对TestNG的兼容性:

<properties>
    <maven-surefire-plugin.version>3.2.5</maven-surefire-plugin.version>
    <!-- 其他属性保持不变 -->
</properties>

建议优先尝试方案1或方案2,这两个是解决此类问题最常见的手段,一般能快速解决Maven不识别TestNG测试的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:57:34