Spring Boot如何在JUnit测试中自动注入@ConfigurationProperties标注的Bean
解决方案
问题根源
注入失败是两个核心原因导致的:
- 使用了
MockitoJUnitRunner,该Runner只会初始化Mockito相关的Mock能力,不会启动Spring上下文,因此@Autowired注解完全不会生效 - 你的
@ConfigurationProperties配置类没有被Spring正确注册为容器中的Bean,也没有启用配置属性绑定能力
具体修复步骤
第一步:修正配置类定义
@ConfigurationProperties需要指定配置前缀,同时要开启Spring对该类的识别,还要提供属性的getter/setter用于配置绑定:
// 可选方案1:给配置类加@Component注解,让组件扫描直接识别到 @Component @ConfigurationProperties(prefix = "my.config") // 替换为你实际的配置前缀 public class ConfigClass{ private String property; // 必须提供getter和setter方法,配置绑定通过setter实现 public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } }
如果不想给配置类加@Component,也可以在启动类/测试类上添加@EnableConfigurationProperties(ConfigClass.class)手动注册配置类。
第二步:修改测试类配置
替换测试Runner为Spring的测试Runner,添加上下文加载注解,确保Spring容器启动:
// JUnit4版本写法 @RunWith(SpringRunner.class) @SpringBootTest // 加载Spring Boot上下文 class MyTests{ @Autowired private ConfigClass configClass; @Test public void myTest1(){ String prop = configClass.getProperty(); // 你的断言逻辑 } }
轻量测试方案(无需加载全量上下文)
如果你的测试只需要用到配置类,不需要加载其他Spring Bean,可以用轻量配置减少启动时间:
@RunWith(SpringRunner.class) @EnableConfigurationProperties(ConfigClass.class) // 直接指定测试用的配置值,也可以指定classpath下的配置文件 @TestPropertySource(properties = "my.config.property=test-value") class MyTests{ @Autowired private ConfigClass configClass; @Test public void myTest1(){ assertEquals("test-value", configClass.getProperty()); } }
注意事项
- 如果使用JUnit5,不需要加
@RunWith注解,替换为@ExtendWith(SpringExtension.class)即可,@SpringBootTest已经默认集成了该扩展,可以直接省略 - 确保你的
application.properties/application.yml中存在对应前缀的配置项,否则绑定完成后属性值会为null - 如果需要结合Mockito使用Mock Bean,可以在测试类中使用
@MockBean注解定义需要Mock的Bean,Spring测试原生支持和Mockito集成 - 确保测试类所在的包路径和Spring Boot主启动类的包路径一致,否则可能出现组件扫描不到配置类的问题,也可以通过
@SpringBootTest(scanBasePackages = "你的包路径")手动指定扫描范围
内容的提问来源于stack exchange,提问作者Kiran Channayanamath
相关产品推荐
相关产品推荐

