Sub topic 13
Testing auto-configuration in isolation
This chapter assumes you can write a Spring Boot auto-configuration with @ConditionalOnClass, @ConditionalOnProperty and @ConditionalOnMissingBean. It also assumes you know JUnit 5 and basic AssertJ assertions. The class under test is the GreetingAutoConfiguration from the previous chapter.
Why not use @SpringBootTest
@SpringBootTest starts a full application. Every auto-configuration on the classpath runs, so you cannot tell whether a bean exists because of your class or because of another one. Each test also pays for a full startup, and changing the classpath or the bean set between tests is awkward.
ApplicationContextRunner solves this. It builds a small application context that contains only the configuration you list. Each call to run creates a fresh context, runs your assertions and closes the context.
The working model
The runner is immutable. Methods such as withConfiguration, withPropertyValues and withBean return a new runner, so you can share a base runner in a field and add settings per test.
Register auto-configurations with AutoConfigurations.of(...), not as plain classes. This wrapper makes the runner process them the way Spring Boot does, including the before and after ordering from the earlier chapter. A plain @Configuration class passed to withUserConfiguration is processed as user configuration instead.
A complete test class
The three tests below cover the three behaviors of GreetingAutoConfiguration.
package com.example.greeting;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class GreetingAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class));
@Test
void createsDefaultBean() {
this.contextRunner.run(context -> assertThat(context).hasSingleBean(GreetingService.class));
}
@Test
void backsOffWhenDisabled() {
this.contextRunner.withPropertyValues("greeting.enabled=false")
.run(context -> assertThat(context).doesNotHaveBean(GreetingService.class));
}
@Test
void backsOffWhenUserDefinesBean() {
GreetingService custom = new GreetingService("custom");
this.contextRunner.withBean(GreetingService.class, () -> custom)
.run(context -> assertThat(context.getBean(GreetingService.class)).isSameAs(custom));
}
}createsDefaultBeanchecks the default path. No property is set, somatchIfMissing = truelets the condition pass.backsOffWhenDisabledsetsgreeting.enabled=false, so the@ConditionalOnPropertycheck fails and no bean is created.backsOffWhenUserDefinesBeanregisters a bean first.isSameAsproves that the auto-configured bean did not replace it.
Common errors
- Passing the class to
withUserConfiguration. User configuration is processed before auto-configuration, so tests of@ConditionalOnBeanand ordering can give results that differ from a real application. - Asserting on a context that failed to start. If startup throws,
runpasses you a context in a failed state. CallinggetBeanthen throws a confusing error. CheckassertThat(context).hasNotFailed()first when a test unexpectedly breaks. UsehasFailed()when you expect failure. - Using the context after
runreturns. The context is closed when the callback ends. Do all assertions inside the lambda. - Forgetting the dependencies of the class under test. If your auto-configuration needs a
DataSource, add the configuration that provides it, or supply a bean withwithBean.
Testing ordering-sensitive configurations
AuditAutoConfiguration uses @ConditionalOnBean(DataSource.class) and after = DataSourceAutoConfiguration.class. To test it, list both classes in AutoConfigurations.of(...), with an embedded database on the test classpath, and assert that AuditLogger exists. Then run it again without DataSourceAutoConfiguration and assert that AuditLogger is absent. The first run exercises the ordering. The second run exercises the condition.
Exercise
A test calls contextRunner.withPropertyValues("greeting.enabled=false") and then, in a second test, calls contextRunner.run(...) with no properties. Does the second test still see greeting.enabled=false? Explain why.
Show answer
No. ApplicationContextRunner is immutable. withPropertyValues returns a new runner and leaves the original unchanged, so the shared field still has no properties and the second test sees the default behavior.
Exercise
Why should you register the class with AutoConfigurations.of(GreetingAutoConfiguration.class) instead of withUserConfiguration?
Show answer
AutoConfigurations.of makes the runner treat the class as an auto-configuration. It is processed after user configuration and its ordering attributes are honored. This matches real application behavior, which matters for @ConditionalOnBean and @ConditionalOnMissingBean.