Spring Boot:@TestConfiguration在集成测试期间不会覆盖Bean [英] Spring Boot: @TestConfiguration Not Overriding Bean During Integration Test

查看:87
本文介绍了Spring Boot:@TestConfiguration在集成测试期间不会覆盖Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用@Configuration装饰的类中定义了 Bean :

I have a Bean defined in a class decorated with @Configuration:

@Configuration
public class MyBeanConfig {

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

我有一个用@TestConfiguration装饰的类,该类应覆盖此 Bean :

I have a class decorated with @TestConfiguration that should override this Bean:

@TestConfiguration
public class MyTestConfiguration {

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

configPath bean用于将外部文件的路径设置为包含在启动期间必须读取的注册码.在@Component类中使用它:

The configPath bean is used to set the path to an external file containing a registration code that must be read during startup. It is used in an @Component class:

@Component
public class MyParsingComponent {

    private String CONFIG_PATH;

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

在尝试调试时,我在每个方法以及测试配置类的构造函数中设置了一个断点. @TestConfiguration 的构造函数断点被击中,所以我知道我的测试配置类实例化,但是该类的 configPath()方法从未被击中.而是,单击常规@Configuration类的 configPath()方法,并在 MyParsingComponent 中的 @Autowired String 始终是 ../production/environment/path ,而不是预期的/test/environment/path .

While trying to debug this, i set a breakpoint inside each method as well as the constructor of the test config class. The @TestConfiguration's constructor breakpoint is hit, so i know that my test configuration class instantiates, however the configPath() method of that class is never hit. Instead, the configPath() method of the normal @Configuration class is hit and the @Autowired String in MyParsingComponent is always ../production/environment/path rather than the expected /test/environment/path.

不确定为什么会这样.任何想法将不胜感激.

Not sure why this is happening. Any thoughts would be greatly appreciated.

推荐答案

As documented in the Detecting Test Configuration section of the Spring Boot reference manual, any beans configured in a top-level class annotated with @TestConfiguration will not be picked up via component scanning. So you have to explicitly register your @TestConfiguration class.

您可以通过测试类上的 @Import(MyTestConfiguration.class) @ContextConfiguration(classes = MyTestConfiguration.class)来实现.

You can do that either via @Import(MyTestConfiguration.class) or @ContextConfiguration(classes = MyTestConfiguration.class) on your test class.

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

On the other hand, if your class annotated with @TestConfiguration were a static nested class within your test class, it would be registered automatically.

这篇关于Spring Boot:@TestConfiguration在集成测试期间不会覆盖Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆