Spring Boot测试中如何配置@PropertySource的classpath路径?
问题分析与解决方案
为什么当前配置不生效?
你在待测试类的@PropertySource中指定了file:前缀,这个前缀会强制Spring以文件系统的方式加载资源,完全忽略你在resources.properties变量中写入的classpath:前缀。Spring会把classpath:/Resources.properties当作普通文件系统路径解析,自然找不到对应文件,因此抛出FileNotFoundException。
解决方案
根据是否能修改待测试类源码,分两种处理方式:
方式一:修改待测试类的@PropertySource(推荐)
如果可以修改待测试类代码,直接去掉@PropertySource中的file:前缀,让配置变量自主决定资源加载方式:
@PropertySource("${resources.properties}") public class SomeController { // 类内容 }
之后在测试环境的test.properties中配置:
resources.properties=classpath:/Resources.properties
生产环境依然可以使用file:前缀的路径(如resources.properties=file:C:/Users/User/Resources.properties),Spring会根据前缀自动选择对应的资源加载策略。
方式二:不修改待测试类源码(适配不可修改场景)
如果无法修改待测试类的@PropertySource,可以在测试类中通过动态属性配置,将resources.properties指向classpath资源的真实文件路径:
@SpringBootTest public class SomeControllerTest { @DynamicPropertySource static void configureProperties(DynamicPropertyRegistry registry) { try { // 获取classpath下资源的真实文件路径 File resourceFile = org.springframework.util.ResourceUtils.getFile("classpath:/Resources.properties"); registry.add("resources.properties", resourceFile::getAbsolutePath); } catch (java.io.FileNotFoundException e) { throw new RuntimeException("测试资源文件不存在", e); } } // 测试方法 @Test void testSomething() { // 测试逻辑 } }
这种方式会在测试启动时动态生成resources.properties的值,指向classpath资源在文件系统中的真实路径,既满足@PropertySource("file:${resources.properties}")的加载要求,又不依赖本地机器的固定路径。
内容的提问来源于stack exchange,提问作者Tomas
相关产品推荐
相关产品推荐

