Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing @ConditionalOnClass autoconfigurations

We have developed a number of 'in-house' Spring Boot Starters & autoconfigurations supporting various NFRs such as logging, configuration, security, etc.

The biggest testing challenge we face is how to test different combinations of @ConditionalOnClass autoconfigurations.

For example:

@Configuration
@ConditionalOnClass(Foo.class)
public class Config1 {

}

@Configuration
@ConditionalOnClass(Bar.class)
public class Config2 {

}

@Configuration
@ConditionalOnMissingClass(Foo.class)
public class Config3 {

}    

How can we manipulate a test project's classpath to test various combinations of Foo & Bar jar files being present on the classapth? Are there any libraries out there? I wonder how the Spring guys do this?

like image 962
got_bainne Avatar asked Dec 29 '25 05:12

got_bainne


1 Answers

I think what you're looking for is the ApplicationContextRunner.

@Test
public void whenDependentClassIsNotPresent_thenBeanMissing() {
    new ApplicationContextRunner().withUserConfiguration(ConditionalOnClassConfiguration.class)
        .withClassLoader(new FilteredClassLoader(DependentClass.class))
        .run(context -> assertThat(context).doesNotHaveBean(BeanConditionalOnDependentClass.class));
}

Source: https://www.baeldung.com/spring-boot-context-runner

like image 200
Jimeh Avatar answered Dec 30 '25 22:12

Jimeh