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

SpringBoot 2.2.2.RELEASE中IntegrationTest与SpringApplicationConfiguration无法识别问题问询

问题原因

你使用的Spring Boot 2.2.2.RELEASE属于2.x正式版本,而@SpringApplicationConfiguration、@IntegrationTest两个注解是Spring Boot 1.x版本的测试专用注解,早在Spring Boot 1.4版本就已经被标记为废弃,2.x版本后已正式从spring-boot-test包中移除,因此编译时无法找到对应的类。

解决方法

Spring Boot 2.x版本将旧测试注解的所有功能整合到了@SpringBootTest注解中,你可以根据自己项目使用的JUnit版本选择对应修改方案:

方案1:兼容JUnit4的写法

如果你的项目仍在使用JUnit4,先调整spring-boot-starter-test依赖,排除默认内置的JUnit5依赖,添加JUnit4兼容引擎:

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

再修改测试类代码如下:

import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServiceTest {

    @org.junit.Test
    public void testAllNames() {
    }
}

方案2:使用官方推荐的JUnit5写法(无需额外调整依赖)

Spring Boot 2.2.x默认集成JUnit5作为测试框架,直接修改测试类代码即可:

import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;

@SpringBootTest(classes = MyApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ServiceTest {

    @Test
    public void testAllNames() {
    }
}

补充说明

  • 原@IntegrationTest启动完整集成环境的功能,对应@SpringBootTest的webEnvironment属性,设置为RANDOM_PORT会随机启动端口,设置为DEFINED_PORT会使用配置文件指定的端口
  • 原@SpringApplicationConfiguration指定启动类的功能,对应@SpringBootTest的classes属性
  • 如果不需要启动web容器仅测试普通业务Bean,可以将webEnvironment属性调整为SpringBootTest.WebEnvironment.NONE,测试启动速度更快

内容的提问来源于stack exchange,提问作者Nunyet Calçada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 11:06:02