用途:为 Spring Boot 的 @ConfigurationProperties 类编写快速单元测试,验证属性绑定、名称映射、类型转换、校验约束、嵌套结构、集合与 profile 专属配置,无需启动完整 Spring 上下文。
主要能力:使用 ApplicationContextRunner 测试属性绑定与默认值;用 @Validated 配合 @NotBlank、@Min、@Max、@Email、@Positive 等约束验证非法值被拒绝(通过 context.hasFailed() 断言);验证 Duration(30s)、DataSize(50MB)、List、Map 等类型转换;测试 dev、prod 等环境专属配置与嵌套属性。
使用方式:添加 spring-boot-starter-test、assertj-core 及 spring-boot-configuration-processor 依赖;确保 @ConfigurationProperties(prefix="...") 与测试属性路径一致;用 withPropertyValues() 提供属性、withBean() 注册配置类,再在 run() 中断言。profile 测试可在 withPropertyValues() 中设置 spring.profiles.active=profileName。
限制与注意:属性名 kebab-case 映射到 Java camelCase;Spring Boot 默认宽松绑定;校验需显式加 @Validated;构造器绑定要求所有参数可绑定;列表用 [0]、[1] 顺序索引;Duration 接受 ISO-8601(PT30S)或 30s、1m、2h 等简写;每个 ApplicationContextRunner 创建独立上下文,不共享状态。嵌套属性、profile 配置、集合绑定与高级校验模式见 references/advanced-examples.md。
适用场景:需要快速、隔离地验证配置类行为,避免完整 Spring 上下文启动开销的测试场景。