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

Spring Boot集成测试中@TestPropertySource无法加载YAML配置求助

Spring Boot集成测试加载YAML配置失败的解决方案

核心问题原因

Spring Boot的@TestPropertySource默认不支持YAML格式,@PropertySource本身也仅默认识别properties/xml文件。即便你自定义了YamlPropertyLoaderFactory,也可能因配置加载优先级、路径格式错误等问题导致失效。最简洁可靠的解决方式是利用Spring Boot原生的Profile配置机制。

最优解决方案:通过Profile自动加载YAML

Spring Boot会根据激活的Profile自动匹配加载对应配置文件,无需手动指定路径,步骤如下:

  1. 将application-test.yaml放置在src/test/resources目录下(与原properties文件位置一致)
  2. 修改测试类,移除@TestPropertySource,改用@SpringBootTest指定激活test Profile,或添加@ActiveProfiles("test")

修改后的测试类代码:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, profiles = "test")
@AutoConfigureMockMvc
public class GlobalExceptionHandlerIntTests {
    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("提交无效数据返回Bad Request")
    public void whenPostInvalidData_thenBadRequest() throws Exception {
        String invalidDataJson = "{\"name\":\"\",\"email\":-1,\"password\":\"\"}";

        mockMvc.perform(MockMvcRequestBuilders.post("/signup")
                        .content(invalidDataJson)
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.status").value(400))
                // 剩余断言逻辑
                ...
    }
}

备选方案:修复@TestPropertySource加载YAML的问题

如果坚持手动指定配置文件,需注意以下两点:

  • 移除@TestPropertySource的properties属性中的空格,正确格式应为:
    @TestPropertySource(properties = {"spring.config.location=classpath:application-test.yaml"})
    
  • 若使用@PropertySource配合自定义Factory,需确保Factory类正确实现PropertySourceFactory,测试类上同时添加@PropertySource和@SpringBootTest,示例:
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    @PropertySource(value = "classpath:application-test.yaml", factory = YamlPropertyLoaderFactory.class)
    @AutoConfigureMockMvc
    public class GlobalExceptionHandlerIntTests {
        // 原有代码
    }
    
    自定义Factory参考实现:
    public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            if (resource == null) {
                return super.createPropertySource(name, resource);
            }
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            Properties properties = factory.getObject();
            return new PropertiesPropertySource(resource.getResource().getFilename(), properties);
        }
    }
    

验证配置是否加载成功

可在测试类中注入Environment,打印配置项确认:

@Autowired
private Environment env;

@Test
public void verifyConfigLoaded() {
    // 替换为你的配置键
    String configValue = env.getProperty("your.test.config.key");
    System.out.println("加载的配置值:" + configValue);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:45:59