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

升级Spring Boot 3与maven-surefire-plugin后TestNG测试被忽略

问题描述

我有一个应用,此前使用Maven执行TestNG测试完全正常,例如执行mvn clean install命令时。目前我将应用升级为使用Spring Boot 3.1.0,现在测试被完全忽略,没有任何测试被执行。我在maven-surefire-plugin中配置了标准的testng.xml文件:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${maven-surefire-plugin.version}</version>
    <configuration>
        <suiteXmlFiles>
            <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
        </suiteXmlFiles>
    </configuration>
</plugin>

我找到的所有解决方案都与以*Test.java结尾的Java类相关,但这不适用于我,因为我使用的是TestNG套件文件,且升级前测试运行正常。Spring Boot 3中哪些变更导致我的测试被跳过?

问题原因及解决方案

Spring Boot 3.1.0对Maven Surefire插件的默认行为做了关键变更:它会自动接管Surefire插件的配置,覆盖你自定义的suiteXmlFiles设置。

具体来说,Spring Boot的spring-boot-maven-plugin在3.1.0版本中,默认启用了test目标的专属配置,内置了测试类筛选规则,这会直接忽略你通过testng.xml指定的测试套件。

以下是两种可行的解决办法:

  • 显式绕过Spring Boot对Surefire的自动配置
    在你的maven-surefire-plugin配置中添加useSystemClassLoader参数并设为true,避免Spring Boot的类加载逻辑干扰套件执行:
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>${maven-surefire-plugin.version}</version>
        <configuration>
            <suiteXmlFiles>
                <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
            </suiteXmlFiles>
            <useSystemClassLoader>true</useSystemClassLoader>
        </configuration>
    </plugin>
    
    或者,在spring-boot-maven-plugin中关闭测试自动配置:
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <skipTests>false</skipTests>
            <excludes>
                <exclude>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-test-autoconfigure</artifactId>
                </exclude>
            </excludes>
        </configuration>
    </plugin>
    
  • 将TestNG套件整合到Spring Boot测试规则中
    若不想修改插件配置,可以创建一个符合*Test.java命名规则的测试类,用@Suite注解指定你的xml套件:
    import org.testng.annotations.Suite;
    
    @Suite(xmlFile = "src/test/resources/testng.xml")
    public class TestSuiteRunnerTest {}
    
    Spring Boot的默认测试扫描规则会识别这个类,进而执行整个TestNG套件。

另外需要注意:Spring Boot 3.x要求TestNG版本至少为7.4.0,检查你的pom.xml中TestNG的版本是否达标,版本过低也可能引发兼容性问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:32:49