Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring ApplicationContextRunner: check conditional assembly in isolation

Last updated: 29 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

ApplicationContextRunner creates a small configurable application context for a test and closes it after the test callback.

Download Spring source kit

This lesson uses the downloadable source kit: Java 21, Spring Boot 4.0.8 and its managed Spring Framework 7 dependencies. The version is pinned for repeatable builds.

Test the branch that backs off

The fallback exporter configuration is valid only when a user exporter is missing. One runner starts with no user bean and expects fallback; the other registers custom and expects exactly one exporter with that behavior.

The second test is essential. A fallback that also registers beside custom would pass the empty-case test while breaking real applications with type ambiguity. The assertion checks the candidate count and the selected behavior.

Context tests are not request tests

No web server starts in this fixture. The result establishes conditional assembly, not routing or security. A class present on the test classpath can also change conditions, so keep the dependency set consistent with the consumer being tested.

When publishing a custom starter, add tests for registration metadata and ordering as well. This lesson checks the small condition used in the kit; it does not claim the kit is a published starter.

Checked source

Java
new ApplicationContextRunner().withBean("custom", ContainerContracts.Exporter.class, () -> () -> "custom")
    .withUserConfiguration(FallbackExportConfig.class)
    .run(context -> {
        assertEquals(1, context.getBeansOfType(ContainerContracts.Exporter.class).size());
        assertEquals("custom", context.getBean(ContainerContracts.Exporter.class).format());
    });

Test the boundary

Run mvn test in the source-kit directory. CoreBoundaryTest.fallbackBeanBacksOffWhenUserBeanExists checks the behavior described here. Java excerpts belong to the named source-kit classes; they are not independent source files unless the complete class is shown.

Costs and boundaries

The runner initializes only the selected configuration and supplied beans. This reduces unrelated assembly work while deliberately excluding full-application behavior.

Common Mistakes

  • Test the user-bean branch as well as the empty branch.
  • Do not infer HTTP behavior from a non-web context.
  • A test classpath can affect conditional assembly.

Read next

Spring Boot auto-configuration: conditions and user-defined beans, Spring qualifiers: select a collaborator when types are ambiguous, Spring tests: separate business rules, wiring and transport.

spring
spring-boot
context-testing
Storage details