1

How to load configuration with @ConditionalOnProperty annotation in unit test in Unit Test ?

I have below @Configuration and @Component

@Configuration
@ConditionalOnProperty(value = {"batch"}, havingValue = "Crawler")
public class CrawlerConfiguration
{   
    @Bean
    @Profile("production")
    public Crawler crawler(@Value("${name}") String name)
    {
        return new Crawler(name, true);
    }

    @Bean
    @Profile("test")
    public Crawler crawlerTest(@Value("${name}") String name)
    {
        return new Crawler(name, false);
    }

}


@Component
public class Crawler implements ApplicationRunner
{
    private String name;
    private boolean withScheduler;

    public Crawler(String name, boolean withScheduler)
    {
        this.name = name;
        this.withScheduler = withScheduler;
    }
    @Override
    public void run(ApplicationArguments args) throws Exception
    {
        // do something
    }
}

Unit test.

@RunWith(SpringRunner.class)
@SpringBootTest(classes={CrawlerConfiguration.class})
public class CrawlerTest 
{
    @Autowired
    private Crawler crawler;

    @Test
    public void run() throws Exception
    {
        crawler.run(new DefaultApplicationArguments(new String[]{}));
    }
}

Running this test gives me alert like this.

=========================

AUTO-CONFIGURATION REPORT

Positive matches:

Negative matches:

CrawlerConfiguration: Did not match: - @ConditionalOnProperty (batch=Crawler) did not find property 'batch' (OnPropertyCondition)

Exclusions:

None

Unconditional classes:

None
Tsuyoshi
  • 27
  • 1
  • 5
  • Refer this answer https://stackoverflow.com/questions/26394778/what-is-purpose-of-conditionalonproperty-annotation – NKR Mar 26 '18 at 16:03

1 Answers1

0

Resolved by Adding properties at @SpringBootTest... Something like below.

@SpringBootTest(classes={CrawlerConfiguration.class}, properties = {"batch=Crawler", "name=myName"})
Tsuyoshi
  • 27
  • 1
  • 5