Spring Boot: @TestConfiguration Not Overriding Bean During Integration Test

前端 未结 3 1810
感情败类
感情败类 2020-12-25 10:24

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

@Configuration
public class MyBeanConfig {

    @Bean
    public String configPa         


        
相关标签:
3条回答
  • 2020-12-25 11:04

    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.

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

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

    0 讨论(0)
  • 2020-12-25 11:10

    Make sure that the method name of your @Bean factory method does not match any existing bean name. I had issues with method names like config() or (in my case) prometheusConfig() which collided with existing bean names. Spring skips those factory methods silently and simply does not call them / does not instantiate the beans.

    If you want to override a bean definition in your test, use the bean name explicitly as string parameter in your @Bean("beanName") annotation.

    0 讨论(0)
  • 2020-12-25 11:17
    • Test configuration has to be explicitly imported in the test via @Import({MyTestConfiguration.class}).
    • The name of the @Bean methods in @Configuration and @TestConfiguration have to be different. At least it makes difference in Spring Boot v2.2.
    • Also make sure spring.main.allow-bean-definition-overriding=true otherwise the bean could not be overriden.
    0 讨论(0)
提交回复
热议问题