【问题标题】:Spring tests - use real bean to create test beanSpring 测试 - 使用真正的 bean 创建测试 bean
【发布时间】:2019-07-18 14:44:37
【问题描述】:

我使用 Spring,并创建了一个使用 SpringRunner 加载上下文的测试。

我有一个看起来像这样的 bean:

@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 并用我的“替换”它(使用实际的)?

【问题讨论】:

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

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2017-10-23
    • 2014-05-15
    • 1970-01-01
    相关资源
    最近更新 更多