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

@SpringBootTest测试配置编译错误:无法找到ServerApplication类求助

解决Maven多模块集成测试找不到ServerApplication类的问题

针对你遇到的问题,以下是几个排查和解决的方向:

1. 修正依赖配置与范围

确保api-int-tests-module的pom.xml中对api-application-module的依赖配置正确,避免使用provided或system这类不会将依赖类加入测试类路径的scope:

<dependency>
    <groupId>你的父项目GroupId</groupId>
    <artifactId>api-application-module</artifactId>
    <version>${project.version}</version>
    <scope>test</scope> <!-- 仅测试代码需要,用test范围足够 -->
</dependency>

如果api-application-module是Spring Boot应用,需配置spring-boot-maven-plugin生成普通jar供测试依赖:

<!-- 在api-application-module的pom.xml中添加 -->
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>${spring-boot.version}</version>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <classifier>exec</classifier> <!-- 生成可执行jar的同时保留普通jar -->
    </configuration>
</plugin>

2. 确认模块构建顺序

父项目的pom.xml中需按依赖顺序声明模块,先构建api-application-module再构建测试模块,确保测试模块能获取到应用模块的编译产物:

<modules>
    <module>api-application-module</module>
    <module>api-int-tests-module</module>
</modules>

3. 调整@SpringBootTest配置(关键)

由于你的集成测试运行在独立Docker容器中,调用的是另一个容器内的应用实例,不需要在测试代码中启动ServerApplication上下文。此时移除@SpringBootTest的classes参数,改用无上下文模式:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@TestPropertySource(locations = "classpath:test-config.properties")
public class ApiIntTests {
    // 用RestTemplate或WebClient调用远程应用容器的接口
    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void testApi() {
        String response = restTemplate.getForObject("http://api-application-container:8080/your-endpoint", String.class);
        // 断言逻辑
    }
}

如果确实需要在测试模块内启动应用上下文(比如本地调试),则确保依赖配置正确后,再保留@SpringBootTest(classes = ServerApplication.class)。

4. 清理Maven缓存并重新构建

执行以下命令强制更新依赖、清理缓存并重新构建所有模块:

mvn clean install -U

5. 核对包名与类路径

确认ServerApplication的包名拼写正确,测试类中import语句的包名、类名与实际完全一致,注意大小写和路径层级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 20:46:16