如何在不使用@SpringBootTest的情况下测试@ConfigurationProperties注解类
不加载全上下文测试@ConfigurationProperties的解决方案
核心思路
不用@SpringBootTest加载完整应用上下文,仅针对目标配置类做属性绑定测试,通过以下注解组合实现:
@ExtendWith(SpringExtension.class):启用Spring测试框架支持@EnableConfigurationProperties(YourProperties.class):激活配置属性绑定逻辑- 配合属性源加载注解,处理
application.yml或自定义测试配置文件
步骤1:补全依赖
如果测试中要读取YAML格式配置,需在POM中添加snakeyaml依赖(Spring Boot生产环境默认包含,但测试环境需显式引入):
<dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <scope>test</scope> </dependency>
同时保留基础测试依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
步骤2:生产配置类示例
假设你的配置类结构如下:
@ConfigurationProperties(prefix = "demo") public class DemoProperties { private String name; private int age; // 省略getter、setter方法 }
步骤3:编写单元测试
方式1:加载外部YAML配置文件
先自定义YamlPropertySourceFactory以支持YAML文件解析:
public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); factory.afterPropertiesSet(); Properties properties = factory.getObject(); return new PropertiesPropertySource( name != null ? name : resource.getResource().getFilename(), properties ); } }
然后编写测试类:
@ExtendWith(SpringExtension.class) @EnableConfigurationProperties(DemoProperties.class) @TestPropertySource( locations = "classpath:application.yml", factory = YamlPropertySourceFactory.class ) public class DemoPropertiesTest { @Autowired private DemoProperties demoProperties; @Test void testPropertiesBinding() { // 断言属性是否正确加载 assertEquals("test-demo-name", demoProperties.getName()); assertEquals(30, demoProperties.getAge()); } }
方式2:直接注入测试属性(无需配置文件)
如果不需要依赖外部配置文件,可直接在注解中指定属性值:
@ExtendWith(SpringExtension.class) @EnableConfigurationProperties(DemoProperties.class) @TestPropertySource(properties = { "demo.name=test-demo-name", "demo.age=30" }) public class DemoPropertiesTest { @Autowired private DemoProperties demoProperties; @Test void testPropertiesBinding() { assertEquals("test-demo-name", demoProperties.getName()); assertEquals(30, demoProperties.getAge()); } }
常见问题排查
- 遗漏
@EnableConfigurationProperties:这是激活配置属性绑定的核心注解,缺少的话配置类只会被实例化,但不会读取配置文件中的属性 - YAML文件路径错误:确保
application.yml放在src/test/resources目录下,或@TestPropertySource指定的路径准确 - 依赖缺失:未添加
snakeyaml会导致YAML文件无法解析,出现属性绑定失败
内容的提问来源于stack exchange,提问作者Tomasz Kamiński
相关产品推荐
相关产品推荐

