java / intermediate
Snippet
Verifying Conditional Bean Registration with ApplicationContextRunner
The ApplicationContextRunner utility enables testing conditional configuration and bean registration rules in isolated contexts without bootstrapping a complete Spring Boot application. It creates an ephemeral context to execute assertions against bean existence, types, or configuration fallbacks.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class CacheAutoConfigurationTest {private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(CacheAutoConfiguration.class);@Testvoid shouldRegisterInMemoryCacheWhenPropertySet() {contextRunner.withPropertyValues("app.cache.type=memory").run(context -> {assertThat(context).hasSingleBean(InMemoryCache.class);assertThat(context).doesNotHaveBean(RedisCache.class);});}@Testvoid shouldBackOffWhenDisabled() {contextRunner.withPropertyValues("app.cache.enabled=false").run(context -> assertThat(context).doesNotHaveBean(CacheManager.class));}}
spring
Breakdown
1
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner().withUserConfiguration(CacheAutoConfiguration.class);
Configures an isolated non-web test context runner with the targeted configuration class.
2
.withPropertyValues("app.cache.type=memory")
Simulates environment properties to evaluate conditional annotations like @ConditionalOnProperty.
3
assertThat(context).hasSingleBean(InMemoryCache.class);
Asserts that exactly one matching bean exists in the dynamically evaluated context.