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

Gradle 7.6测试任务未将src/test/resources纳入Spring Boot类路径问题

解决方案

原因分析

问题出在@PropertySource的资源路径未指定classpath:前缀,默认会从ServletContext根路径加载资源,而测试环境下ServletContext的资源路径与项目类路径(src/main/resources、src/test/resources)不匹配,导致无法找到配置文件。

可行方案

方案1:改用Spring Boot原生Profile机制(推荐)

Spring Boot原生支持环境Profile,无需自定义ENV变量,更符合框架规范:

  1. 将配置文件命名为application-unit.properties(规范用小写,Spring Profile默认大小写不敏感)
  2. 测试类中使用@ActiveProfiles指定测试环境:
@SpringBootTest
@ActiveProfiles("unit")
class SampleAppTest {
  // ...code
}
  1. 移除启动类中的@PropertySource注解,Spring Boot会自动根据激活的Profile加载对应配置文件。

方案2:修改@PropertySource路径为类路径

如果坚持使用自定义ENV变量,只需给资源路径加上classpath:前缀,让Spring从类路径(包含main和test的resources目录)加载配置:

@SpringBootApplication
@PropertySource(value = "classpath:application-${ENV:LOCAL}.properties", ignoreResourceNotFound = false)
public class SampleApp {
  // ...code
}

测试类保持原有配置即可,此时Spring会从类路径中找到application-UNIT.properties。

方案3:调整测试环境变量的设置方式

将测试类中的@TestPropertySource替换为@SpringBootTest的properties参数,确保环境变量在@PropertySource解析前生效:

@SpringBootTest(properties = {"ENV=UNIT"})
class SampleAppTest {
  // ...code
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:34:54