Loading the right bean in the test profile in Spring boot

82 Views Asked by At

My application.yaml has the following entries:

spring:
  profiles:
    active: test
    include: h2, test
key:
 enabled: on

I have the following three bean definitions and would like to load the TestConfig bean in my tests. But it takes NoConfig Bean in the tests:

    @ConditionalOnProperty(name = "key.enabled", matchIfMissing = true)
    @Profile("test")
    public class TestConfig {}

    @ConditionalOnMissingBean(Config.class)
    public class NoConfig {}

   @ConditionalOnProperty(name = "key.enabled", matchIfMissing = true)
   @Profile("!test")
   public class Config{}

I also check the active profile in the test, and it is indeed test profile.

@Value("${spring.profiles.active:Unknown}")
private String activeProfile;
1

There are 1 best solutions below

4
Сестренка 8 лет On

Bean NoConfig you have is always created when there is no bean Config. You can try to use @TestConfiguration to define beans needed for a particular test, or you can write a BeanFactoryPostProcessor to exclude unnecessary bean from initialisation

Or try to add havingValue attribute in @ConditionalOnProperty annotation and change key.enabled attribute in yaml file to set the value of it to true