Sub topic 12
Testing Auto-Configuration with ApplicationContextRunner
This chapter shows how to test an auto-configuration without starting a full Spring Boot application. It assumes you know beans, @Configuration, conditional annotations, and @ConfigurationProperties. It also assumes you have JUnit 5 and AssertJ on the test classpath, which spring-boot-starter-test provides.
Why not use @SpringBootTest?
@SpringBootTest starts the whole application. That is slow, and it loads every auto-configuration on the classpath. When you test one auto-configuration, other configurations can hide the behavior you want to check.
ApplicationContextRunner starts a small context for each test. You choose which configurations to load. You can change the classpath, properties, and user beans per test. This makes it a good fit for conditional logic.
The code under test
The examples test the greeting auto-configuration from the previous chapters. It defines a GreetingService bean only if the application has not defined one. It reads the greeting.message property.
@AutoConfiguration
@ConditionalOnClass(GreetingService.class)
@EnableConfigurationProperties(GreetingProperties.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public GreetingService greetingService(GreetingProperties properties) {
return new GreetingService(properties.getMessage());
}
}Creating the runner
Create the runner as a field, and register your auto-configuration with AutoConfigurations.of(...). Using AutoConfigurations instead of a plain class matters. It applies the same ordering rules that Boot uses for real auto-configurations.
class GreetingAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class));
@Test
void createsDefaultBean() {
contextRunner.run(context -> {
assertThat(context).hasSingleBean(GreetingService.class);
assertThat(context.getBean(GreetingService.class).greet("Ann")).isEqualTo("Hello, Ann!");
});
}
@Test
void backsOffWhenUserDefinesBean() {
contextRunner
.withBean(GreetingService.class, () -> new GreetingService("Hi"))
.run(context -> assertThat(context.getBean(GreetingService.class).greet("Ann")).isEqualTo("Hi, Ann!"));
}
}The runner is immutable. Each with... call returns a new runner, so the shared field is safe to reuse across tests. Each run call starts a fresh context and closes it when the lambda finishes.
How a test runs
Changing the inputs
Each test varies one input and checks the result. These are the most useful methods.
| Method | What it does |
|---|---|
| `withPropertyValues("a=b")` | Sets properties for this test only |
| `withBean(Type.class, supplier)` | Adds a user-defined bean |
| `withUserConfiguration(Config.class)` | Adds a user `@Configuration` class |
| `withClassLoader(new FilteredClassLoader(X.class))` | Hides a class to simulate a missing dependency |
Testing properties
Set a property and check that the bean uses it.
@Test
void usesConfiguredMessage() {
contextRunner
.withPropertyValues("greeting.message=Welcome")
.run(context ->
assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Welcome, Ann!"));
}Testing a missing class
@ConditionalOnClass is hard to test with a normal classpath because the class is present. FilteredClassLoader hides it.
@Test
void doesNotCreateBeanWhenClassIsMissing() {
contextRunner
.withClassLoader(new FilteredClassLoader(GreetingService.class))
.run(context -> assertThat(context).doesNotHaveBean("greetingService"));
}The test checks the bean by name. If it checked the type, the lookup itself would need the hidden class.
Common errors
- Registering the class with
withUserConfiguration. Conditions such as@ConditionalOnMissingBeanare evaluated in a different order for user configurations. UsewithConfiguration(AutoConfigurations.of(...))for the class under test. - Asserting outside the lambda. The context closes when
runreturns. Make all assertions inside the lambda. - Forgetting that a startup failure is a result. If the context fails to start,
context.getStartupFailure()holds the exception. UseassertThat(context).hasFailed()to test that invalid input is rejected. - Using
@SpringBootTestfor conditional logic. It works, but it is slower and loads unrelated auto-configurations.
Exercise
You test @ConditionalOnClass(GreetingService.class), but GreetingService is on the test classpath, so the condition always matches. Which runner feature lets you test the case where the class is absent, and how do you assert the result?
Show answer
Call withClassLoader(new FilteredClassLoader(GreetingService.class)) on the runner. Then, inside run, assert that the bean is absent by name, for example assertThat(context).doesNotHaveBean("greetingService").
Exercise
Why should you register the auto-configuration with AutoConfigurations.of(...) and not withUserConfiguration(...)?
Show answer
AutoConfigurations applies Boot's auto-configuration ordering, so conditions like @ConditionalOnMissingBean are evaluated as they are in a real application. withUserConfiguration treats the class as a user configuration, which can change the evaluation order and give misleading results.