Java Spring测试-使用真实bean创建测试bean

Java Spring测试-使用真实bean创建测试bean,java,spring,spring-boot,spring-test,spring-bean,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

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

在Spring测试中,您必须模拟bean或
@SpyBean
来监视bean:

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

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


我认为您可以使用@EnableConfigurationProperties,这样您就可以从测试以及主应用程序中访问相同的属性。如果您只想更改属性,您还可以通过使用例如:
@TestPropertySource(properties={“A=B”、“C=D”、“E=F”})覆盖测试中所需的属性。