Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/spring-projects/spring-boot/llms.txt

Use this file to discover all available pages before exploring further.

Spring Boot packages several utility classes in spring-boot-test that help with common testing concerns: capturing console output, injecting inline properties, testing auto-configurations in isolation, and making HTTP calls without a running server. These utilities work independently of @SpringBootTest and can be used in any JUnit 5 test.

OutputCaptureExtension

OutputCaptureExtension is a JUnit 5 Extension that captures System.out and System.err output during a test. Apply it with @ExtendWith and inject a CapturedOutput argument into your test method or lifecycle methods:
@ExtendWith(OutputCaptureExtension.class)
class MyOutputCaptureTests {

    @Test
    void testName(CapturedOutput output) {
        System.out.println("Hello World!");
        assertThat(output).contains("World");
    }

}
The CapturedOutput object exposes both streams separately via getOut() and getErr(), so you can assert on stdout and stderr independently in @AfterEach methods.
To reliably capture output from Java Util Logging (JUL), reset its configuration after each test by calling LogManager.getLogManager().readConfiguration() in an @AfterEach method. For Log4j2, set the follow attribute of the console appender to true.

TestPropertyValues

TestPropertyValues lets you add inline property overrides to a ConfigurableEnvironment or ConfigurableApplicationContext using key=value or key:value strings. It is particularly useful in ApplicationContextRunner-based tests (see below) and in custom ApplicationContextInitializer implementations:
class MyEnvironmentTests {

    @Test
    void testPropertySources() {
        MockEnvironment environment = new MockEnvironment();
        TestPropertyValues.of("org=Spring", "name=Boot").applyTo(environment);
        assertThat(environment.getProperty("name")).isEqualTo("Boot");
    }

}
TestPropertyValues.of(...) returns an immutable instance. Calling and(...) produces a new instance with additional entries, so you can safely compose property sets without mutating existing ones.

ApplicationContextRunner

ApplicationContextRunner is the primary tool for testing auto-configurations in isolation, without the overhead of @SpringBootTest. It creates a lightweight ApplicationContext, applies your configuration, and passes the result to a ContextConsumer lambda where you can make AssertJ assertions. The context is closed automatically after each consumer completes. A typical use is to declare the runner as a field on the test class, then use it in individual test methods:
class MyServiceAutoConfigurationTests {

    private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(MyServiceAutoConfiguration.class));

    @Test
    void serviceNameCanBeConfigured() {
        this.contextRunner.withPropertyValues("user.name=test123").run((context) -> {
            assertThat(context).hasSingleBean(MyService.class);
            assertThat(context.getBean(MyService.class).getName()).isEqualTo("test123");
        });
    }

    @Test
    void serviceIsIgnoredIfLibraryIsNotPresent() {
        this.contextRunner.withClassLoader(new FilteredClassLoader(MyService.class))
            .run((context) -> assertThat(context).doesNotHaveBean("myService"));
    }

    @Test
    void defaultServiceBacksOff() {
        this.contextRunner.withUserConfiguration(UserConfiguration.class).run((context) -> {
            assertThat(context).hasSingleBean(MyService.class);
            assertThat(context).getBean("myCustomService").isSameAs(context.getBean(MyService.class));
        });
    }

    @Configuration(proxyBeanMethods = false)
    static class UserConfiguration {

        @Bean
        MyService myCustomService() {
            return new MyService("mine");
        }

    }

}
The runner API is fluent and composable. Common methods include:
Registers auto-configurations to apply to the context. Use AutoConfigurations.of(MyAutoConfig.class) for auto-configurations and UserConfigurations.of(MyConfig.class) for user-supplied beans.
Adds inline property overrides using key=value pairs. Equivalent to calling TestPropertyValues.of(...) on the runner’s environment.
Registers additional @Configuration classes alongside the auto-configurations under test. Useful for providing beans that the auto-configuration expects to find (or back off from).
Replaces the default class loader. Use FilteredClassLoader to simulate the absence of a library and verify conditional auto-configuration behavior.
Runs the runner and passes the resulting AssertableApplicationContext to the consumer. If the context fails to start, the consumer receives a “failed” context and assertions that require a running context will fail. Use getFailure() to assert on the cause.
For reactive web contexts use ReactiveWebApplicationContextRunner, and for servlet-based web contexts use WebApplicationContextRunner. Both share the same fluent API as ApplicationContextRunner.

ConfigDataApplicationContextInitializer

ConfigDataApplicationContextInitializer is an ApplicationContextInitializer that loads Spring Boot’s application.properties and application.yaml files into the Environment. Use it when you need property file loading in a plain @ContextConfiguration test, without the full @SpringBootTest machinery:
@ContextConfiguration(classes = Config.class, initializers = ConfigDataApplicationContextInitializer.class)
class MyConfigFileTests {

    // application.properties values are available via @Value or Environment

}
ConfigDataApplicationContextInitializer alone does not enable @Value("${...}") injection. Its only job is loading config files into the Environment. For @Value support, also configure a PropertySourcesPlaceholderConfigurer, or switch to @SpringBootTest which auto-configures one.

TestRestTemplate

TestRestTemplate is a convenience alternative to Spring’s RestTemplate designed for integration tests. It is fault tolerant: rather than throwing exceptions on 4xx and 5xx responses, it returns a ResponseEntity containing the status code, letting you assert on error scenarios without wrapping calls in try-catch blocks. You can instantiate it directly in a test:
class MyTests {

    private final TestRestTemplate template = new TestRestTemplate();

    @Test
    void testRequest() {
        ResponseEntity<String> response = this.template.getForEntity(
                "https://myhost.example.com/example", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    }

}
When using @SpringBootTest with RANDOM_PORT or DEFINED_PORT, annotate the test class with @AutoConfigureTestRestTemplate to get a fully configured TestRestTemplate autowired into the test. URLs that omit the host and port are automatically resolved against the embedded server:
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureTestRestTemplate
class MySpringBootTests {

    @Autowired
    private TestRestTemplate template;

    @Test
    void testRequest() {
        ResponseEntity<String> response = this.template.getForEntity("/example", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    }

    @TestConfiguration(proxyBeanMethods = false)
    static class RestTemplateBuilderConfiguration {

        @Bean
        RestTemplateBuilder restTemplateBuilder() {
            return new RestTemplateBuilder()
                    .connectTimeout(Duration.ofSeconds(1))
                    .readTimeout(Duration.ofSeconds(1));
        }

    }

}
TestRestTemplate is provided by the spring-boot-resttestclient module and also requires a spring-boot-restclient dependency. Adding spring-boot-restclient enables auto-configuration for RestClient.Builder, so declare it on the main classpath (not just the test classpath) if your production code uses RestClient.Builder.For a fluent, AssertJ-friendly alternative, consider RestTestClient, which works in both mock and real-server environments and provides dedicated assertion methods on the response.

Build docs developers (and LLMs) love