春季测试-使用真实的bean创建测试bean

时间:2019-02-25 08:23:48

标签: java spring spring-boot spring-test spring-bean

我使用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)?

1 个答案:

答案 0 :(得分:2)

在Spring Test中,您有@MockBean来模拟bean或@SpyBean来监视bean:

  

Spring Boot包含一个@MockBean批注,可用于为ApplicationContext中的bean定义Mockito模拟。您可以使用批注添加新bean或替换单个现有bean定义。

     

此外,您可以使用@SpyBean用Mockito间谍包装任何现有的bean