Spring Boot测试中如何mock@ConfigurationProperties类加载测试配置
问题场景
我有一个业务类,会自动装配(@Autowired)另一个标注了@ConfigurationProperties注解的配置类。
带@ConfigurationProperties的配置类
@ConfigurationProperties(prefix = "report") public class SomeProperties { private String property1; private String property2; // 省略其他字段 }
自动装配配置类的业务服务
@Service @Transactional public class SomeService { @Autowired private SomeProperties someProperties; // 其他业务逻辑 }
遇到的问题
现在需要测试SomeService类,在测试类中mockSomeProperties类时,所有属性值都获取到的是null。当前测试类写法如下:
@RunWith(SpringRunner.class) @SpringBootTest(classes = SomeProperties.class) @ActiveProfiles("test") @EnableConfigurationProperties public class SomeServiceTest { @InjectMocks private SomeService someService; @Mock // 也尝试过使用@MockBean,同样没有生效 private SomeProperties someProperties; }
核心诉求:如何对SomeProperties进行处理,使其属性值来源于application-test.properties配置文件?
问题根因
现有写法混用了Mockito测试框架和Spring Boot测试框架的注入链路,两者的运行逻辑完全独立,导致属性全为null:
@Mock生成的纯Mockito mock对象,默认所有方法返回值都是null,不会触发Spring的配置绑定流程,根本不会读取application-test.properties里的配置@InjectMocks只会把Mockito生成的mock实例手动注入到被测的SomeService里,完全绕开了Spring的属性装配、配置绑定逻辑- 之前尝试的
@MockBean不生效,是因为测试类上@SpringBootTest(classes = SomeProperties.class)只把SomeProperties注册成了普通Spring Bean,没有执行“读取配置文件、把对应前缀的属性值填充到Bean字段”的完整绑定流程,就算替换了Bean实例,里面的属性依然是空值。
解决方案
根据实际测试需求选择对应实现:
不需要手动mock,直接使用配置文件的真实值
如果测试目标就是验证业务逻辑读取真实配置的运行情况,完全不需要写mock相关注解,正确开启配置绑定流程即可:
- 删掉测试类上所有
@Mock、@InjectMocks相关的注解和字段 - 调整测试注解配置,保证Spring能正常加载配置文件、完成属性绑定:
@RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") // 显式指定需要开启属性绑定的配置类 @EnableConfigurationProperties(SomeProperties.class) public class SomeServiceTest { // 直接从Spring上下文注入完成绑定的实例 @Autowired private SomeService someService; }
运行测试时,Spring会自动将application-test.properties中report前缀的配置项绑定到SomeProperties的对应字段,再注入到SomeService中,不会出现null值问题。
需要按需mock部分逻辑,同时保留配置文件的真实值
如果测试过程中需要对SomeProperties的个别返回值做自定义打桩,同时希望其余属性保持从application-test.properties读取的真实值,使用@SpyBean替换原生的mock写法:
@RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") @EnableConfigurationProperties(SomeProperties.class) public class SomeServiceTest { @Autowired private SomeService someService; // 用@SpyBean代替@MockBean,spy实例会默认保留原Bean的所有属性值 @SpyBean private SomeProperties someProperties; @Test public void testBusinessLogic() { // 仅需要自定义返回值的场景手动打桩,其余属性自动从配置文件读取 // when(someProperties.getProperty1()).thenReturn("自定义测试值"); } }
踩坑提醒:如果
SomeProperties类没有为每个字段编写标准的getter、setter方法,Spring的配置绑定流程无法将配置值填充到私有字段,就算注解配置全部正确,字段值依然会是null,记得提前补全对应方法。
内容的提问来源于stack exchange,提问作者Sunil
相关产品推荐
相关产品推荐

