测试模块无法加载application.yml文件的问题求助
排查思路
修正@SpringBootTest的配置
由于模块无main目录,@SpringBootTest无法自动识别启动类,需手动指定要加载的类或配置类,示例:@SpringBootTest(classes = TestProperties.class)确保Spring上下文能正确初始化配置属性相关逻辑。
移除TestProperties类上的@TestPropertySource注解
@SpringBootTest默认会自动加载src/test/resources下的application.yml,额外添加该注解可能干扰默认加载流程,导致配置未生效。验证pom.xml的testResources配置及文件复制情况
检查pom中testResources配置是否正确包含yml文件:<build> <testResources> <testResource> <directory>src/test/resources</directory> <includes> <include>**/*.yml</include> </includes> </testResource> </testResources> </build>执行
mvn clean test-compile后,查看target/test-classes目录下是否存在application.yml,确认文件已被正确复制到测试类路径。验证配置文件是否被加载
在测试类中注入Environment并打印配置值:@Autowired private Environment environment; @Test public void testConfigLoad() { System.out.println(environment.getProperty("abc.def")); }如果能输出
123,说明配置文件已加载,问题出在@ConfigurationProperties的绑定逻辑;如果输出null,说明配置文件未加载,回到前面步骤排查。确保@ConfigurationProperties绑定生效
- 在BaseFunctionalTest上添加
@EnableConfigurationProperties(TestProperties.class),显式启用配置属性绑定; - 检查TestProperties类的字段名与yml配置是否完全一致,确认@Data注解正确生成了getter/setter(可查看编译后的class文件验证);
- 若TestProperties与测试类不在同一包下,需在@SpringBootTest中指定扫描包:
@SpringBootTest(scanBasePackages = "你的配置类所在包路径")
- 在BaseFunctionalTest上添加
内容的提问来源于stack exchange,提问作者Laodao
相关产品推荐
相关产品推荐

