Spring Boot:@TestConfiguration 在集成测试期间不覆盖 Bean

新手上路,请多包涵

我有一个 Bean 在装饰有 @Configuration 的类中定义:

 @Configuration
public class MyBeanConfig {
    @Bean
    public String configPath() {
        return "../production/environment/path";
    }
}

我有一个用 @TestConfiguration 修饰的类,它应该覆盖这个 Bean

 @TestConfiguration
public class MyTestConfiguration {
    @Bean
    @Primary
    public String configPath() {
        return "/test/environment/path";
    }
}

configPath bean 用于设置指向包含启动期间必须读取的注册码的外部文件的路径。它用于 @Component 类:

 @Component
public class MyParsingComponent {
    private String CONFIG_PATH;

    @Autowired
    public void setCONFIG_PATH(String configPath) {
        this.CONFIG_PATH = configPath;
    }
}

在尝试调试时,我在每个方法以及测试配置类的构造函数中设置了一个断点。 @TestConfiguration 的构造函数断点被命中,所以我知道我的测试配置类实例化,但是 configPath 该类的方法永远不会被命中。 Instead, the configPath method of the normal @Configuration class is hit and the @Autowired String in MyParsingComponent is always ../production/environment/path 而不是预期的 /test/environment/path

不知道为什么会这样。任何想法将不胜感激。

原文由 The Head Rush 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 823
2 个回答

如 Spring Boot 参考手册的 检测测试配置 部分所述,在顶级类中配置的任何 beans 注释为 @TestConfiguration不会 通过组件扫描被拾取。所以你必须显式注册你的 @TestConfiguration 类。

您可以通过 @Import(MyTestConfiguration.class)@ContextConfiguration(classes = MyTestConfiguration.class) 在您的测试类上执行此操作。

另一方面,如果用 @TestConfiguration 注释的类是测试类 static 嵌套类,它将自动注册。

原文由 Sam Brannen 发布,翻译遵循 CC BY-SA 4.0 许可协议

确保 @Bean 工厂方法的方法名称不匹配任何现有的 bean 名称。我遇到了方法名称问题,例如 config() 或(在我的例子中) prometheusConfig() 与现有 bean 名称冲突。 Spring 静静地 跳过那些工厂方法,只是不调用它们/不实例化 bean。

如果要在测试中覆盖 bean 定义,请在 @Bean(“beanName”) 注释中明确使用 bean 名称作为字符串参数。

原文由 Marcel Thimm 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题