Sub topic 13
Testing auto-configuration in isolation
This chapter assumes you have read the earlier chapters on @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, @ConfigurationProperties and ordering with @AutoConfiguration(before/after). You should also know JUnit 5 and AssertJ basics. Here you will test the GreetingAutoConfiguration from the custom auto-configuration chapter. The tests check that it applies by default, backs off, binds properties and reacts to a missing class.
Why not @SpringBootTest
A @SpringBootTest starts the whole application with every auto-configuration on the classpath. For a library's auto-configuration this causes three problems:
- Other auto-configurations may add beans or fail, so a test can break for reasons unrelated to your class.
- You cannot easily vary the classpath, so a
@ConditionalOnClassbranch is hard to exercise. - Each variation needs a new context and often a new test class, which is slow.
ApplicationContextRunner is a test helper from spring-boot-test (included in spring-boot-starter-test). It builds a small ApplicationContext containing only the configurations you name. You can change properties, beans and class visibility for each test, and the runner closes the context when the assertions finish.
The runner basics
The tests below need a GreetingService class. This minimal version is enough:
package com.example.greeting;
public class GreetingService {
private final String message;
public GreetingService(String message) {
this.message = message;
}
public String greet(String name) {
return this.message + ", " + name;
}
}The test class from the topic plan follows. It uses one shared runner and three tests.
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));
}
}Each with... method returns a new runner and leaves the original unchanged. Sharing the contextRunner field is therefore safe, because each test adds its own settings to a copy.
Why AutoConfigurations.of matters
withConfiguration(AutoConfigurations.of(...)) registers the class the way Spring Boot registers a real auto-configuration. It is processed after user configuration, and before/after ordering among the listed classes is applied. That is what makes @ConditionalOnMissingBean back-off behave as it does in production.
If you passed GreetingAutoConfiguration to withUserConfiguration(...), it would be treated as ordinary user configuration. It would be processed in registration order, so a back-off test could pass or fail for the wrong reason. Use withUserConfiguration only for configuration that belongs to the test, such as a @Configuration class that defines a replacement bean.
What each test proves
| Test | Condition exercised | Evidence |
|---|---|---|
| `createsDefaultBean` | `matchIfMissing = true` on `@ConditionalOnProperty`, and `@ConditionalOnClass` satisfied | exactly one `GreetingService` |
| `backsOffWhenDisabled` | `greeting.enabled=false` fails `havingValue = "true"` | no `GreetingService` bean |
| `backsOffWhenUserDefinesBean` | `@ConditionalOnMissingBean` | the instance in the context is the user's object |
The third test uses isSameAs rather than hasSingleBean. hasSingleBean would also pass if the auto-configuration replaced the user's bean with its own. Identity shows that the user's bean won.
Testing property binding
@ConfigurationProperties binding is part of the auto-configuration's behavior, so test it too. Add this test to the same class. It also needs import static org.assertj.core.api.Assertions.assertThat;, which you already have.
@Test
void bindsMessageProperty() {
this.contextRunner.withPropertyValues("greeting.message=Howdy")
.run(context -> {
GreetingService service = context.getBean(GreetingService.class);
assertThat(service.greet("Ada")).isEqualTo("Howdy, Ada");
});
}
@Test
void usesDefaultMessage() {
this.contextRunner.run(context -> {
GreetingService service = context.getBean(GreetingService.class);
assertThat(service.greet("Ada")).isEqualTo("Hello, Ada");
});
}withPropertyValues takes key=value strings. They go into the test context's environment, so relaxed binding applies as in a real application.
Testing a missing class
@ConditionalOnClass(GreetingService.class) protects users who do not have the library on the classpath. You cannot remove a class from the test classpath, but you can hide it from the context. FilteredClassLoader does this.
import org.springframework.boot.test.context.FilteredClassLoader;
@Test
void backsOffWhenClassIsMissing() {
this.contextRunner.withClassLoader(new FilteredClassLoader(GreetingService.class))
.run(context -> assertThat(context).doesNotHaveBean("greetingService"));
}The test asserts on the bean name because the context cannot load GreetingService through the filtered loader. A type-based assertion such as doesNotHaveBean(GreetingService.class) could behave unexpectedly in that context, so a name is the safer check. FilteredClassLoader also accepts package names as strings, which is useful for hiding a whole dependency.
For this to test the right thing, @ConditionalOnClass must be on the auto-configuration class itself, as in GreetingAutoConfiguration. Spring reads class-level conditions from bytecode metadata without loading the referenced class. Putting a method signature that mentions a missing class on a bean method inside a class without that guard would cause the very NoClassDefFoundError the condition is meant to prevent.
Testing conditions that depend on order
The AuditAutoConfiguration from the ordering chapter uses @ConditionalOnBean(DataSource.class) and after = DataSourceAutoConfiguration.class. A test must reflect that @ConditionalOnBean only sees bean definitions registered earlier. Supplying a DataSource through withBean is the simplest approach. It does not need a database driver.
package com.example.audit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class AuditAutoConfigurationTests {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(AuditAutoConfiguration.class));
@Test
void backsOffWithoutDataSource() {
this.contextRunner.run(context -> assertThat(context).doesNotHaveBean(AuditLogger.class));
}
@Test
void createsLoggerWhenDataSourceExists() {
this.contextRunner.withBean(DataSource.class, () -> mock(DataSource.class))
.run(context -> assertThat(context).hasSingleBean(AuditLogger.class));
}
}A bean added with withBean is registered before auto-configurations are processed, so the condition sees it. To test the real ordering with DataSourceAutoConfiguration, list both classes in AutoConfigurations.of(DataSourceAutoConfiguration.class, AuditAutoConfiguration.class). Also add an embedded database such as H2 to the test classpath, or set spring.datasource.url. AutoConfigurations sorts the classes by their before and after attributes, so the order you write them in does not matter. If you remove after = ... from AuditAutoConfiguration, that test can start failing, which shows the ordering attribute is doing real work.
Asserting on failures
Some auto-configurations should fail fast, for example when a required property is invalid. The context does not throw from run. It hands you a context that records the failure.
@Test
void startsCleanly() {
this.contextRunner.run(context -> assertThat(context).hasNotFailed());
}hasNotFailed() prints the startup exception when it fails, which is more useful than a bare NullPointerException further down. For a negative case, use assertThat(context).hasFailed() and inspect context.getStartupFailure().
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Registering the auto-configuration with `withUserConfiguration` | Back-off and ordering tests do not match production | Use `withConfiguration(AutoConfigurations.of(...))` |
| Using `hasSingleBean` to prove a user bean won | Passes even if the auto-configuration replaced it | Compare with `isSameAs` |
| Using `@SpringBootTest` for each condition | Slow tests with unrelated beans | Use one runner and vary it per test |
| Reading the context after `run` returns | The context is closed | Make all assertions inside the consumer |
| Forgetting `matchIfMissing = true` in tests | The default case silently fails | Keep a "no properties set" test |
Putting it together
For the greeting auto-configuration you now have six checks: default creation, property binding, greeting.enabled=false, user bean back-off, missing class, and a clean start. Each one is a few lines and starts a context in milliseconds. These tests also document the contract of the library: which switches exist, and what happens when users override a bean.
Exercise
Why does the test backsOffWhenUserDefinesBean assert isSameAs(custom) rather than hasSingleBean(GreetingService.class), and why must the auto-configuration be registered with AutoConfigurations.of rather than withUserConfiguration?
Show answer
hasSingleBean passes whenever exactly one bean of the type exists, even if the auto-configuration had replaced the user's bean with its own. isSameAs(custom) proves the instance in the context is the user's object, so the auto-configuration backed off. AutoConfigurations.of registers the class as a real auto-configuration, processed after user beans and sorted by before/after. With withUserConfiguration it would be handled as ordinary user configuration in registration order, and @ConditionalOnMissingBean would not be tested under production conditions.
Exercise
Write a test for GreetingAutoConfiguration that proves greeting.message=Hi is used when the user has not defined their own GreetingService. Name the runner method that supplies the property.
Show answer
Use withPropertyValues:
this.contextRunner.withPropertyValues("greeting.message=Hi").run(context -> assertThat(context.getBean(GreetingService.class).greet("Ada")).isEqualTo("Hi, Ada"));
The assertion goes inside the run consumer because the context is closed once the consumer returns.