我使用Spring,并创建了一个使用SpringRunner加载上下文的测试。
我有一个看起来像这样的豆子:
@Bean
public Properties kafkaStreamsProperties(){
final Properties props = new Properties();
props.put("A", "B");
props.put("C", "D");
return props;
}
我想在测试中将其扩展为还包含属性“ E”->“ F”。
我可以在内部@TestConfiguration类中轻松完成此操作,如下所示:
public class test{
public static class MyConfig{
@Bean
public Properties kafkaStreamsProperties(){
final Properties props = new Properties();
props.put("A", "B");
props.put("C", "D");
props.put("E", "F");
return props;
}
}
}
但是当我更改生产代码时,我也必须“记住”更改测试。有什么办法可以从上下文中获取实际的bean,并用我的“替换”它(使用实际的bean)?
答案 0 :(得分:2)
在Spring Test中,您有@MockBean来模拟bean或@SpyBean
来监视bean:
Spring Boot包含一个@MockBean批注,可用于为ApplicationContext中的bean定义Mockito模拟。您可以使用批注添加新bean或替换单个现有bean定义。
此外,您可以使用@SpyBean用Mockito间谍包装任何现有的bean