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

添加@SpringBootTest注解后Maven未执行对应测试的问题求助

问题描述
  • 项目环境:Spring Boot 2.7.18,Maven 3.9.6
  • 依赖配置:pom.xml包含maven-surefire-plugin 2.22.2、spring-boot-starter-web、spring-boot-test、JUnit 5.8.2
  • 测试类规范:所有测试类均以Tests.java结尾
  • 测试代码示例:
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
// 其他导入

@SpringBootTest(properties={"testproperty=value"})
public class ExampleTests {
    @Test
    public void ExampleValidTest() {
        // 测试逻辑
    }
}
  • 问题现象:执行mvn clean package时,不带@SpringBootTest的测试正常执行,但带该注解的测试完全不运行;移除注解后测试能执行,但会因缺少指定属性而失败。
解决办法

1. 给Surefire插件添加JUnit 5支持

Maven Surefire 2.22.2默认对JUnit 5的支持不完善,需要手动添加provider依赖。在pom.xml的build/plugins节点下修改surefire插件配置:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <dependencies>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-surefire-provider</artifactId>
            <version>1.8.2</version> <!-- 和你的JUnit 5.8.2版本匹配 -->
        </dependency>
    </dependencies>
</plugin>

2. 升级Surefire插件版本

2.22.2版本太老,Spring Boot 2.7.x建议用3.0.0以上的Surefire版本,新版本对JUnit 5支持更友好,无需额外配置provider。修改pom.xml中的插件版本:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.0.0-M9</version> <!-- 此版本兼容Spring Boot 2.7.x -->
</plugin>

3. 指定Spring Boot启动类

如果测试类不在主应用类的包或子包下,@SpringBootTest可能找不到上下文配置导致测试被跳过。可以显式指定启动类:

@SpringBootTest(classes = YourMainApplication.class, properties={"testproperty=value"})

把YourMainApplication换成你项目里的Spring Boot启动类。

4. 查看调试日志找原因

执行mvn clean package -X开启调试模式,仔细看日志里关于ExampleTests的部分,通常能找到测试被跳过的具体原因(比如上下文初始化失败、测试类未被识别等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 19:23:00