Sub topic 12
Testing auto-configuration with ApplicationContextRunner
This chapter assumes you have read the earlier chapters on conditional annotations, @ConfigurationProperties, and writing a custom auto-configuration. It also assumes you know JUnit 5 and AssertJ basics. The examples test the GreetingAutoConfiguration built in that chapter.
Why not just use @SpringBootTest?
An auto-configuration makes decisions: create this bean, skip that one, bind these properties. You want a test for each decision. @SpringBootTest is a poor fit for that, for three reasons:
- It starts the whole application, so each test is slow.
- Your test application's own beans and component scan can hide the behavior you want to check.
- Changing the classpath or a property between tests is awkward.
ApplicationContextRunner is a test utility in spring-boot-test. It builds a small ApplicationContext for each test, with only the configuration you give it. It starts quickly, and you can change properties, beans, and even the visible classes for each test. Spring Boot's own auto-configurations are tested this way.
Both ApplicationContextRunner and the assertions you use with it come from spring-boot-starter-test, which you add in test scope:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>How a runner test works
A runner is an immutable description of a context. You call with... methods to describe it, then call run with a lambda that makes assertions. The runner creates the context, passes it to your lambda, and closes it when the lambda returns.
Every with... call returns a new runner and leaves the original unchanged. You can therefore define one base runner as a field and customize it per test without tests affecting each other.
The base runner
The base runner registers your auto-configuration with AutoConfigurations.of(...):
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class));AutoConfigurations is not the same as plain configuration classes. It applies the auto-configuration rules: it sorts classes by @AutoConfigureBefore, @AutoConfigureAfter, and @AutoConfigureOrder, and it processes them after user configuration. That is what makes @ConditionalOnMissingBean behave as it does in a real application.
Testing the default behavior
The first test checks that a bare context with only your auto-configuration produces the default bean:
@Test
void createsDefaultBean() {
contextRunner.run(context -> {
assertThat(context).hasSingleBean(GreetingService.class);
assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Hello, Ann!");
});
}context is an AssertableApplicationContext. Passing it to AssertJ's assertThat gives you context-specific assertions:
| Assertion | Passes when |
|---|---|
| `hasSingleBean(Type.class)` | Exactly one bean of that type exists |
| `doesNotHaveBean(Type.class)` | No bean of that type exists |
| `hasBean("name")` | A bean with that name exists |
| `hasNotFailed()` | The context started without an exception |
| `hasFailed()` | The context failed to start |
| `getFailure()` | Returns the startup exception, for further assertions |
Testing property binding
Use withPropertyValues with key=value strings. They behave like entries in application.properties, so they also exercise the relaxed binding of @ConfigurationProperties:
@Test
void messageCanBeChangedWithProperty() {
contextRunner
.withPropertyValues("greeting.message=Welcome")
.run(context -> assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Welcome, Ann!"));
}This one test covers three things at once: the greeting prefix, the message field name, and the bean method passing properties.getMessage() to the constructor. A typo in any of them fails the test.
Testing back-off
Back-off is the behavior most auto-configurations are valued for, and the easiest to break. You can test it in two ways.
withBean registers a single bean, which is convenient for simple cases:
contextRunner
.withBean(GreetingService.class, () -> new GreetingService("Hi"))
.run(context -> assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Hi, Ann!"));withUserConfiguration registers a whole @Configuration class, which is closer to how real applications define overrides:
@Configuration(proxyBeanMethods = false)
static class CustomGreetingConfiguration {
@Bean
GreetingService greetingService() {
return new GreetingService("Hi");
}
}contextRunner
.withUserConfiguration(CustomGreetingConfiguration.class)
.run(context -> {
assertThat(context).hasSingleBean(GreetingService.class);
assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Hi, Ann!");
});The hasSingleBean assertion matters here. If @ConditionalOnMissingBean were missing from the auto-configuration, the context would contain two GreetingService beans. The test would then fail instead of passing by luck on a getBean call that picks one.
Testing @ConditionalOnClass with FilteredClassLoader
You cannot remove a class from the test classpath, but you can hide it from the context. FilteredClassLoader wraps the class loader so that the named classes, packages, or resources appear to be missing:
@Test
void backsOffWhenClassIsMissing() {
contextRunner
.withClassLoader(new FilteredClassLoader(GreetingService.class))
.run(context -> assertThat(context).doesNotHaveBean(GreetingService.class));
}This only works if the condition is on the auto-configuration class, or if it is on a nested class or a @Bean method that does not load the missing type early. A @ConditionalOnClass on a @Bean method whose return type is the missing class is a common mistake. Put the condition on the class or on a nested configuration class instead. Spring reads annotations with ASM, so naming the class in the annotation is safe, but the class loader cannot be asked to load it.
The full test class
Here is everything together. It also tests the registration file, which ApplicationContextRunner never reads:
package com.example.greeting;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.annotation.ImportCandidates;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
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 messageCanBeChangedWithProperty() {
contextRunner
.withPropertyValues("greeting.message=Welcome")
.run(context -> assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Welcome, Ann!"));
}
@Test
void backsOffWhenUserDefinesBean() {
contextRunner
.withUserConfiguration(CustomGreetingConfiguration.class)
.run(context -> {
assertThat(context).hasSingleBean(GreetingService.class);
assertThat(context.getBean(GreetingService.class).greet("Ann"))
.isEqualTo("Hi, Ann!");
});
}
@Test
void backsOffWhenClassIsMissing() {
contextRunner
.withClassLoader(new FilteredClassLoader(GreetingService.class))
.run(context -> assertThat(context).doesNotHaveBean(GreetingService.class));
}
@Test
void isListedInImportsFile() {
List<String> candidates = new ArrayList<>();
ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader())
.forEach(candidates::add);
assertThat(candidates).contains(GreetingAutoConfiguration.class.getName());
}
@Configuration(proxyBeanMethods = false)
static class CustomGreetingConfiguration {
@Bean
GreetingService greetingService() {
return new GreetingService("Hi");
}
}
}Common mistakes
- Escaping the context. The context closes when
runreturns. Do not store it in a field or use it after the lambda. Do all assertions inside. - Forgetting
AutoConfigurations.withConfiguration(UserConfigurations.of(...))treats your class as user configuration.@ConditionalOnMissingBeanthen sees it in the wrong order, and back-off tests can pass or fail for the wrong reason. - Assuming the imports file is tested. The runner is given the class directly. A missing or misspelled line in
AutoConfiguration.importspasses every runner test and fails only in a real application. TheisListedInImportsFiletest above guards against that. - Leaking state between tests. Do not mutate the shared runner. Because
with...returns a copy, assigning the result back to the field in one test would change every later test. - Asserting only the happy path. For every condition in your auto-configuration, write one test where it matches and one where it does not.
Related runners and helpers
WebApplicationContextRunnerandReactiveWebApplicationContextRunnerstart a servlet or reactive web context. Use them when your conditions include@ConditionalOnWebApplication.withInitializeradds anApplicationContextInitializer. Addingnew ConditionEvaluationReportLoggingListener(LogLevel.INFO)prints the conditions report for a test, which helps when a condition does not match as you expected.withSystemPropertiesandwithPropertyValuesset inputs for conditions such as@ConditionalOnProperty.
Exercise
You add @ConditionalOnProperty(prefix = "greeting", name = "enabled", havingValue = "true", matchIfMissing = true) to GreetingAutoConfiguration. Which two runner tests would you add, and what does each assert?
Show answer
First, a test with withPropertyValues("greeting.enabled=false") that asserts doesNotHaveBean(GreetingService.class), which proves the condition turns the bean off. Second, a test with no greeting.enabled property (the existing createsDefaultBean test already covers this) that asserts hasSingleBean(GreetingService.class), which proves matchIfMissing = true keeps the default behavior.
Exercise
A back-off test uses withConfiguration(AutoConfigurations.of(GreetingAutoConfiguration.class)) and withBean(GreetingService.class, ...), and asserts getBean(GreetingService.class) returns the user's message. Someone deletes @ConditionalOnMissingBean from the auto-configuration, but the test still passes. How do you change the test so it fails?
Show answer
Add assertThat(context).hasSingleBean(GreetingService.class) inside the run lambda. Without the condition, the context holds two beans of that type, so this assertion fails. A bare getBean call can pick the user's bean (or fail with a different error) and does not prove that the auto-configuration backed off.