Advanced Spring testing: contexts, overrides and side effects

Once a test suite has a few hundred Spring tests, its speed and reliability depend on details: how often a context is started, how beans and properties are replaced, and what a test transaction really rolls back. This page runs each of those mechanisms and shows where they surprise people, from a nested @Configuration that hides the application to a REQUIRES_NEW write that survives the rollback.

Contents

What the TestContext framework does for each test

Every Spring test, whether it uses @SpringBootTest, a slice annotation or plain @ContextConfiguration, runs through the Spring TestContext framework. For each test class it works out a merged configuration: the configuration classes, active profiles, test properties, bean overrides and customizers that the class's annotations add up to. That merged configuration is the key of a cache of application contexts.

Before a test class runs, the framework looks the key up. If a context with the same key already exists, the test gets it at once; otherwise the framework starts a new one and stores it. Test execution listeners then do the per-test work: injecting fields, starting and rolling back test transactions, running @Sql scripts, resetting mocks and recording events. Most of the surprises in larger test suites come from one of two things: a key that differs when you did not expect it, which costs a new context, or a listener that does something you did not expect, such as rolling back.

The test features on this page
FeatureFromSinceWhat it is for
Context cacheSpring Framework2.5Starting each distinct configuration only once
Context pausingSpring Framework7.0Stopping background work in cached contexts not in use
@TestBeanSpring Framework6.2Replacing a bean with one built by a factory method
@TestConfigurationSpring Boot1.4Adding beans to the application's configuration in a test
@DynamicPropertySourceSpring Framework5.2.5Properties whose values are known only at run time
@Sql, @Commit, @AfterTransactionSpring Framework2.5 to 4.2Test data and test transactions
MockRestServiceServerSpring Framework3.2; RestClient support in 6.1Testing code that calls other services
@RecordApplicationEventsSpring Framework5.3.3Asserting on published application events
OutputCaptureExtensionSpring Boot2.2Asserting on console and log output
ApplicationContextRunnerSpring Boot2.0Testing configuration and auto-configuration quickly

All programs run with Spring Boot 4.1 and JUnit 6. As on the Spring Boot testing page, each program holds the application and its tests, and its main method runs the tests with the JUnit Platform launcher. A logback-test.xml on the classpath sets the log level to WARN, as many projects do in src/test/resources.

Context caching, measured

Six test classes extend the same base class, and each one changes one thing about its configuration, or nothing. A component counts how many times it is created, which is once per application context:

Java
package demo.advanced.caching;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.bean.override.mockito.MockitoBean;

public class ContextCaching {

    static final AtomicInteger STARTS = new AtomicInteger();

    @SpringBootApplication
    static class ShopApplication {
    }

    // created once per application context, so it counts context starts
    @Component
    static class StartCounter {
        final int number = STARTS.incrementAndGet();
    }

    @Service
    static class MailService {
    }

    @SpringBootTest(properties = "spring.main.banner-mode=off")
    abstract static class BaseTest {
        @Autowired
        StartCounter counter;

        @Autowired
        ApplicationContext context;

        @Test
        void report() {
            System.out.printf("  %-24s context #%d%n", getClass().getSimpleName(), counter.number);
            assertThat(context).isNotNull();
        }
    }

    static class OrderTest extends BaseTest {
    }

    static class InvoiceTest extends BaseTest {
    }

    static class MailMockTest extends BaseTest {
        @MockitoBean
        MailService mail;
    }

    @ActiveProfiles("eu")
    static class EuProfileTest extends BaseTest {
    }

    @DirtiesContext
    static class DirtyTest extends BaseTest {
    }

    static class AfterDirtyTest extends BaseTest {
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectClass(OrderTest.class),
                                DiscoverySelectors.selectClass(InvoiceTest.class),
                                DiscoverySelectors.selectClass(MailMockTest.class),
                                DiscoverySelectors.selectClass(EuProfileTest.class),
                                DiscoverySelectors.selectClass(DirtyTest.class),
                                DiscoverySelectors.selectClass(AfterDirtyTest.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        // print failures only: each test prints its own line
                        if (id.isTest()
                                && result.getStatus() != TestExecutionResult.Status.SUCCESSFUL) {
                            System.out.println(id.getDisplayName() + ": " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
        System.out.println("Six test classes started " + STARTS.get() + " contexts");
    }
}
Output
OrderTest                context #1
  InvoiceTest              context #1
  MailMockTest             context #2
  EuProfileTest            context #3
  DirtyTest                context #1
  AfterDirtyTest           context #4
Six test classes started 4 contexts
  • OrderTest started context 1, and InvoiceTest, with the same configuration, reused it. That reuse is the whole point of the cache.
  • MailMockTest added one @MockitoBean, and got context 2. Bean overrides are part of the cache key, because a context with a mock in it is a different context.
  • EuProfileTest activated a profile and got context 3. Profiles, test properties and @DynamicPropertySource methods are part of the key too.
  • DirtyTest had the same configuration as the first two, so it reused context 1. Its @DirtiesContext then closed that context after the class finished.
  • AfterDirtyTest also had the first configuration, but context 1 was gone, so it started context 4. In total, six classes cost four starts instead of six, and a suite without @DirtiesContext and with fewer distinct overrides would have cost two.

The cache holds at most 32 contexts by default and evicts the least recently used one when it is full; the spring.test.context.cache.maxSize system property changes the limit. Each cached context keeps its beans, thread pools and database connections alive until it is evicted or the JVM ends. Since Spring Framework 7.0 the framework also pauses a cached context when a test switches to a different one, stopping its scheduled tasks and message listeners until a test uses it again. Setting logging.level.org.springframework.test.context.cache=DEBUG logs the hit and miss counts, which is the quickest way to find out why a suite starts more contexts than expected.

Replacing and adding beans

An invoice service that computes a due date from Clock is hard to test with the real clock, because the expected date changes every day. The program replaces the clock, adds a recording audit sink, and shows a nested configuration class that silently replaces the whole application:

Java
package demo.advanced.testbeans;

import static org.assertj.core.api.Assertions.assertThat;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.test.context.bean.override.convention.TestBean;

public class TestBeans {

    interface AuditSink {
        void record(String entry);
    }

    @SpringBootApplication
    static class BillingApplication {
        @Bean
        Clock clock() {
            return Clock.systemUTC();
        }

        @Bean
        AuditSink auditSink() {
            return entry -> System.out.println("  (production audit) " + entry);
        }
    }

    @Service
    static class InvoiceService {
        private final Clock clock;
        private final AuditSink audit;

        InvoiceService(Clock clock, AuditSink audit) {
            this.clock = clock;
            this.audit = audit;
        }

        LocalDate dueDate() {
            LocalDate due = LocalDate.now(clock).plusDays(30);
            audit.record("invoice due " + due);
            return due;
        }
    }

    @SpringBootTest(properties = "spring.main.banner-mode=off")
    static class FixedClockTest {
        // replaces the "clock" bean with the result of the static method of the same name
        @TestBean
        Clock clock;

        static Clock clock() {
            return Clock.fixed(Instant.parse("2026-01-15T10:00:00Z"), ZoneOffset.UTC);
        }

        @Autowired
        InvoiceService invoices;

        @Test
        void dueDateIsThirtyDaysAfterToday() {
            System.out.println("  due date: " + invoices.dueDate());
            assertThat(invoices.dueDate()).isEqualTo(LocalDate.of(2026, 2, 14));
        }
    }

    @SpringBootTest(properties = {"spring.main.banner-mode=off",
            "spring.main.allow-bean-definition-overriding=true"})
    static class RecordingAuditTest {
        // a nested @TestConfiguration is added to the application's own configuration
        @TestConfiguration
        static class RecordingAudit {
            final List<String> entries = new ArrayList<>();

            @Bean
            AuditSink auditSink() {
                return entries::add;
            }
        }

        @Autowired
        InvoiceService invoices;

        @Autowired
        RecordingAudit recording;

        @Test
        void recordsTheInvoice() {
            invoices.dueDate();
            System.out.println("  recorded entries: " + recording.entries.size());
            assertThat(recording.entries).hasSize(1);
        }
    }

    @SpringBootTest(properties = "spring.main.banner-mode=off")
    static class NestedConfigurationTest {
        // a nested @Configuration is used INSTEAD of the application's configuration
        @Configuration
        static class OnlyThis {
            @Bean
            String greeting() {
                return "hello";
            }
        }

        @Autowired
        ApplicationContext context;

        @Test
        void invoiceServiceIsMissing() {
            System.out.println("  InvoiceService beans: "
                    + context.getBeanNamesForType(InvoiceService.class).length);
            assertThat(context.getBeanNamesForType(InvoiceService.class)).isEmpty();
        }
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectClass(FixedClockTest.class),
                                DiscoverySelectors.selectClass(RecordingAuditTest.class),
                                DiscoverySelectors.selectClass(NestedConfigurationTest.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        if (id.isTest()) {
                            System.out.println(id.getDisplayName() + ": " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
    }
}
Output
(production audit) invoice due 2026-02-14
  due date: 2026-02-14
  (production audit) invoice due 2026-02-14
dueDateIsThirtyDaysAfterToday(): SUCCESSFUL
  recorded entries: 1
recordsTheInvoice(): SUCCESSFUL
  InvoiceService beans: 0
invoiceServiceIsMissing(): SUCCESSFUL
  • FixedClockTest: @TestBean replaced the clock bean with the result of the static method of the same name, a clock fixed at 15 January 2026. Thirty days later is 14 February, every time the test runs. The production audit sink was still in place, which is why its line was printed twice, once for each call to dueDate().
  • RecordingAuditTest: the nested @TestConfiguration was added to the application's configuration and its auditSink bean took the place of the production one, so the entry was recorded instead of printed. The test configuration class is itself a bean, which is how the test reads its entries.
  • NestedConfigurationTest: a nested class annotated with plain @Configuration was used instead of the application. The context had no InvoiceService at all, and in a real test every @Autowired application bean would fail.

The second test needs spring.main.allow-bean-definition-overriding=true, because the test bean has the same name as the production bean. Without it, the context fails to start with BeanDefinitionOverrideException, "A bean with that name has already been defined ... and overriding is disabled", as a run without the property shows. @TestBean and @MockitoBean do not need the property, because they replace the bean definition instead of adding a second one. Prefer them for replacing beans, and keep @TestConfiguration for adding beans the application does not have, such as a test-only controller or data builder.

Test properties and which one wins

A test can set properties in three places: the properties attribute of @SpringBootTest, @TestPropertySource, and a @DynamicPropertySource method. This program sets four keys so that each pair of sources competes once:

Java
package demo.advanced.properties;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.TestPropertySource;

public class TestProperties {

    @SpringBootApplication
    static class ShopApplication {
    }

    @SpringBootTest(properties = {"spring.main.banner-mode=off",
            "a.only-boot-test=from @SpringBootTest",
            "b.boot-vs-source=from @SpringBootTest",
            "d.boot-vs-dynamic=from @SpringBootTest"})
    @TestPropertySource(properties = {
            "b.boot-vs-source=from @TestPropertySource",
            "c.source-vs-dynamic=from @TestPropertySource"})
    static class PrecedenceTest {
        @DynamicPropertySource
        static void dynamic(DynamicPropertyRegistry registry) {
            // the supplier is called when the property is read, so it can use a value
            // that is only known at run time, such as a container's mapped port
            registry.add("c.source-vs-dynamic", () -> "from @DynamicPropertySource");
            registry.add("d.boot-vs-dynamic", () -> "from @DynamicPropertySource");
        }

        @Autowired
        Environment env;

        @Test
        void showWinners() {
            for (String key : List.of("a.only-boot-test", "b.boot-vs-source",
                    "c.source-vs-dynamic", "d.boot-vs-dynamic")) {
                System.out.printf("  %-20s = %s%n", key, env.getProperty(key));
            }
            assertThat(env.getProperty("c.source-vs-dynamic"))
                    .isEqualTo("from @DynamicPropertySource");
        }
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectClass(PrecedenceTest.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        if (id.isTest()) {
                            System.out.println(id.getDisplayName() + ": " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
    }
}
Output
a.only-boot-test     = from @SpringBootTest
  b.boot-vs-source     = from @TestPropertySource
  c.source-vs-dynamic  = from @DynamicPropertySource
  d.boot-vs-dynamic    = from @DynamicPropertySource
showWinners(): SUCCESSFUL
  • Key a appears only in @SpringBootTest, and that value was used. These properties already beat application.properties and environment variables.
  • Key b was set by both @SpringBootTest and @TestPropertySource, and @TestPropertySource won.
  • Keys c and d show that @DynamicPropertySource beat both of the others. It has the highest precedence of all test property sources.

@DynamicPropertySource exists for values that are only known when the test runs, such as the port of a database started by Testcontainers. The value is a Supplier, called when the property is read, so it can wait until the container has started. Since Spring Framework 6.2, a bean implementing DynamicPropertyRegistrar can register such properties from a configuration class instead of from the test. Because every source is part of the cache key, a property that differs between two test classes gives each its own context.

Transactional tests and what they roll back

A test method annotated with @Transactional runs in a transaction that the framework rolls back when the method ends, so each test starts from the same data. Four tests against one table show the default, the way to keep data, test data from @Sql, and the case that escapes the rollback:

Java
package demo.advanced.tx;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.TestTransaction;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class TransactionalTests {

    @SpringBootApplication
    static class ShopApplication {
        @Bean
        ApplicationRunner schema(JdbcTemplate jdbc) {
            return args -> jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, sku VARCHAR(9))");
        }
    }

    @Service
    static class AuditService {
        private final JdbcTemplate jdbc;

        AuditService(JdbcTemplate jdbc) {
            this.jdbc = jdbc;
        }

        @Transactional(propagation = Propagation.REQUIRES_NEW)
        public void saveInOwnTransaction(int id) {
            jdbc.update("INSERT INTO orders VALUES (?, 'audit')", id);
        }
    }

    @SpringBootTest(properties = "spring.main.banner-mode=off")
    @Transactional
    @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
    static class OrderTableTest {
        @Autowired
        JdbcTemplate jdbc;

        @Autowired
        AuditService audit;

        int count() {
            return jdbc.queryForObject("SELECT COUNT(*) FROM orders", Integer.class);
        }

        @Test
        @Order(1)
        void rolledBackByDefault() {
            jdbc.update("INSERT INTO orders VALUES (1, 'book')");
            System.out.println("  inside the test: " + count() + " row(s), transaction active = "
                    + TestTransaction.isActive());
        }

        @Test
        @Order(2)
        @Commit
        void committedWithCommit() {
            jdbc.update("INSERT INTO orders VALUES (2, 'pen')");
            System.out.println("  inside the test: " + count() + " row(s)");
        }

        @Test
        @Order(3)
        @Sql(statements = {"INSERT INTO orders VALUES (10, 'a')",
                "INSERT INTO orders VALUES (11, 'b')"})
        void sqlRunsInsideTheTestTransaction() {
            System.out.println("  inside the test: " + count() + " row(s)");
            assertThat(count()).isEqualTo(3);
        }

        @Test
        @Order(4)
        void requiresNewEscapesTheRollback() {
            audit.saveInOwnTransaction(20);
            System.out.println("  inside the test: " + count() + " row(s)");
        }

        @AfterTransaction
        void afterEachTransaction() {
            System.out.println("  after the test transaction ended: " + count() + " row(s)");
        }
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectClass(OrderTableTest.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionStarted(TestIdentifier id) {
                        if (id.isTest()) {
                            System.out.println(id.getDisplayName());
                        }
                    }

                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        if (id.isTest()
                                && result.getStatus() != TestExecutionResult.Status.SUCCESSFUL) {
                            System.out.println("  " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
    }
}
Output
rolledBackByDefault()
  inside the test: 1 row(s), transaction active = true
  after the test transaction ended: 0 row(s)
committedWithCommit()
  inside the test: 1 row(s)
  after the test transaction ended: 1 row(s)
sqlRunsInsideTheTestTransaction()
  inside the test: 3 row(s)
  after the test transaction ended: 1 row(s)
requiresNewEscapesTheRollback()
  inside the test: 2 row(s)
  after the test transaction ended: 2 row(s)
  • rolledBackByDefault: the insert was visible inside the test, 1 row, and TestTransaction.isActive() was true. @AfterTransaction ran after the rollback and found 0 rows.
  • committedWithCommit: @Commit turned the rollback into a commit, so row 2 stayed. The table now holds 1 row for the following tests, which is why @Commit is rarely the right choice.
  • sqlRunsInsideTheTestTransaction: @Sql inserted two rows before the test method, inside its transaction. The test saw 3 rows, and afterwards they were rolled back to 1.
  • requiresNewEscapesTheRollback: the service method ran with REQUIRES_NEW, so it committed in its own transaction before returning. The test's rollback could not undo it, and the table ended with 2 rows.

The rollback covers only work done in the test's own transaction, on the test's thread. Writes made with REQUIRES_NEW, on another thread such as an @Async method, by a real HTTP request to a RANDOM_PORT server, or by a message listener all commit for real. A suite that uses those needs to clean up explicitly, for example with an @Sql script that has executionPhase = AFTER_TEST_METHOD. The rollback also hides failures that happen only at commit, such as deferred constraint checks and @TransactionalEventListener handlers. See Spring @Transactional for the propagation rules.

Testing calls to other services

Code that calls another service through RestClient should be tested without that service. MockRestServiceServer replaces the HTTP layer of a RestClient.Builder, checks each request against an expectation and returns a prepared response. This exchange-rate client is tested for a good answer, an error and a wrong request:

Java
package demo.advanced.http;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.response.MockRestResponseCreators;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClient;

public class OutgoingHttp {

    record Rate(String from, String to, BigDecimal rate) {
    }

    // the class under test calls a remote API through RestClient
    static class RateClient {
        private final RestClient http;

        RateClient(RestClient.Builder builder) {
            this.http = builder.baseUrl("https://rates.example.com").build();
        }

        BigDecimal rate(String from, String to) {
            return http.get().uri("/rates/{from}/{to}", from, to)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .body(Rate.class)
                    .rate();
        }
    }

    static class RateClientTest {
        MockRestServiceServer server;
        RateClient client;

        @BeforeEach
        void setUp() {
            RestClient.Builder builder = RestClient.builder();
            server = MockRestServiceServer.bindTo(builder).build();
            client = new RateClient(builder);
        }

        @Test
        void parsesTheRate() {
            server.expect(requestTo("https://rates.example.com/rates/EUR/USD"))
                    .andExpect(method(HttpMethod.GET))
                    .andExpect(header("Accept", "application/json"))
                    .andRespond(withSuccess("""
                            {"from": "EUR", "to": "USD", "rate": 1.0842}""",
                            MediaType.APPLICATION_JSON));

            BigDecimal rate = client.rate("EUR", "USD");
            System.out.println("  rate: " + rate);
            assertThat(rate).isEqualByComparingTo("1.0842");
            server.verify();
        }

        @Test
        void surfacesA503() {
            server.expect(requestTo("https://rates.example.com/rates/EUR/GBP"))
                    .andRespond(MockRestResponseCreators.withServiceUnavailable());

            assertThatThrownBy(() -> client.rate("EUR", "GBP"))
                    .isInstanceOf(HttpServerErrorException.ServiceUnavailable.class)
                    .satisfies(e -> System.out.println("  thrown: " + e.getMessage()));
        }

        @Test
        void unexpectedRequestFails() {
            server.expect(requestTo("https://rates.example.com/rates/EUR/USD"))
                    .andRespond(withSuccess());
            try {
                client.rate("USD", "JPY");
            } catch (AssertionError e) {
                System.out.println("  " + e.getMessage().lines().findFirst().orElse(""));
            }
        }
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectClass(RateClientTest.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        if (id.isTest()) {
                            System.out.println(id.getDisplayName() + ": " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
    }
}
Output
rate: 1.0842
parsesTheRate(): SUCCESSFUL
  thrown: 503 Service Unavailable: [no body]
surfacesA503(): SUCCESSFUL
  Request URI expected:<https://rates.example.com/rates/EUR/USD> but was:<https://rates.example.com/rates/USD/JPY>
unexpectedRequestFails(): SUCCESSFUL
  • The first test checked the URL, the method and the Accept header, returned JSON, and the client turned it into the rate 1.0842. server.verify() fails if an expected request was never made.
  • The 503 response surfaced as HttpServerErrorException.ServiceUnavailable, the specific subclass, with the message 503 Service Unavailable: [no body]. That is the exception a retry or circuit breaker would be configured for.
  • The third test expected a request for EUR to USD and received one for USD to JPY. The mock server threw an AssertionError at once, naming both URLs.

This test needs no application context at all, so it runs as fast as a unit test. It also tests the client with a plain RestClient.Builder, not the one Spring Boot configures. @RestClientTest, from the spring-boot-restclient-test module, starts a small slice instead: the auto-configured builder with Jackson, the component under test, and a MockRestServiceServer bean already bound to that builder. This version of the client reads a snake_case date field, which only works with the property the test sets:

Java
package demo.advanced.restclienttest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

import java.math.BigDecimal;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.restclient.test.autoconfigure.RestClientTest;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;

public class RestClientSlice {

    record Rate(String from, String to, BigDecimal rate, LocalDate quotedOn) {
    }

    @SpringBootApplication
    static class ShopApplication {
    }

    @Service
    static class RateClient {
        private final RestClient http;

        RateClient(RestClient.Builder builder) {      // the builder Spring Boot configures
            this.http = builder.baseUrl("https://rates.example.com").build();
        }

        Rate rate(String from, String to) {
            return http.get().uri("/rates/{from}/{to}", from, to).retrieve().body(Rate.class);
        }
    }

    @Service
    static class InvoiceService {
    }

    @RestClientTest(components = RateClient.class, properties = {
            "spring.main.banner-mode=off", "logging.level.root=WARN",
            "spring.jackson.property-naming-strategy=SNAKE_CASE"})
    static class RateClientSliceTest {
        @Autowired
        RateClient client;

        @Autowired
        MockRestServiceServer server;

        @Autowired
        ApplicationContext context;

        @Test
        void usesTheConfiguredJsonMapper() {
            server.expect(requestTo("https://rates.example.com/rates/EUR/USD"))
                    .andRespond(withSuccess("""
                            {"from": "EUR", "to": "USD", "rate": 1.0842,
                             "quoted_on": "2026-03-09"}""", MediaType.APPLICATION_JSON));
            Rate rate = client.rate("EUR", "USD");
            System.out.println("  " + rate);
            assertThat(rate.quotedOn()).isEqualTo(LocalDate.of(2026, 3, 9));
            server.verify();
        }

        @Test
        void plainBuilderIgnoresBootSettings() {
            RestClient.Builder plain = RestClient.builder();      // not from the context
            MockRestServiceServer own = MockRestServiceServer.bindTo(plain).build();
            own.expect(requestTo("https://rates.example.com/rates/EUR/USD"))
                    .andRespond(withSuccess("""
                            {"from": "EUR", "to": "USD", "rate": 1.0842,
                             "quoted_on": "2026-03-09"}""", MediaType.APPLICATION_JSON));
            System.out.println("  plain builder: " + new RateClient(plain).rate("EUR", "USD"));
        }

        @Test
        void loadsOnlyTheClient() {
            System.out.println("  RateClient beans: "
                    + context.getBeanNamesForType(RateClient.class).length
                    + ", InvoiceService beans: "
                    + context.getBeanNamesForType(InvoiceService.class).length
                    + ", beans in total: " + context.getBeanDefinitionCount());
            assertThat(context.getBeanNamesForType(InvoiceService.class)).isEmpty();
        }

        @Test
        void serverIsResetBetweenTests() {
            server.expect(requestTo("https://rates.example.com/rates/EUR/GBP"))
                    .andRespond(withSuccess("""
                            {"from": "EUR", "to": "GBP", "rate": 0.8391,
                             "quoted_on": "2026-03-10"}""", MediaType.APPLICATION_JSON));
            System.out.println("  " + client.rate("EUR", "GBP"));
            server.verify();
        }
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectClass(RateClientSliceTest.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        if (id.isTest()) {
                            System.out.println(id.getDisplayName() + ": " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
    }
}
Output
Rate[from=EUR, to=USD, rate=1.0842, quotedOn=2026-03-09]
usesTheConfiguredJsonMapper(): SUCCESSFUL
  plain builder: Rate[from=EUR, to=USD, rate=1.0842, quotedOn=null]
plainBuilderIgnoresBootSettings(): SUCCESSFUL
  Rate[from=EUR, to=GBP, rate=0.8391, quotedOn=2026-03-10]
serverIsResetBetweenTests(): SUCCESSFUL
  RateClient beans: 1, InvoiceService beans: 0, beans in total: 51
loadsOnlyTheClient(): SUCCESSFUL
  • The injected client read quoted_on into quotedOn=2026-03-09. Its builder came from the context, so spring.jackson.property-naming-strategy=SNAKE_CASE applied to it, as it would in the running application.
  • The same client built from RestClient.builder() got quotedOn=null: the plain builder knows nothing about Spring Boot's Jackson settings, and Jackson ignored the unknown field. A test like the previous program's would not catch a mapping that depends on configuration.
  • The third test set its own expectation and passed, although the first test had used the server too. Spring Boot resets the MockRestServiceServer bean after each test.
  • The slice held the RateClient named in components, no InvoiceService, and 51 beans in total.

For tests that need a real HTTP server on the other side, WireMock is the usual choice.

Asserting events and log output

Some results of a method are not in its return value: an event it publishes, or a line it writes to the log. Both can be asserted directly. The order service here does both:

Java
package demo.advanced.sideeffects;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.event.RecordApplicationEvents;

public class SideEffects {

    record OrderPlaced(long orderId, String sku) {
    }

    @SpringBootApplication
    static class ShopApplication {
    }

    @Service
    static class OrderService {
        private static final Logger log = LoggerFactory.getLogger("shop.orders");
        private final ApplicationEventPublisher events;

        OrderService(ApplicationEventPublisher events) {
            this.events = events;
        }

        void place(long id, String sku) {
            log.info("order {} placed for {}", id, sku);
            events.publishEvent(new OrderPlaced(id, sku));
        }
    }

    @SpringBootTest(properties = {"spring.main.banner-mode=off",
            "logging.level.shop.orders=INFO"})
    @RecordApplicationEvents
    @ExtendWith(OutputCaptureExtension.class)
    static class OrderServiceTest {
        @Autowired
        OrderService orders;

        @Autowired
        ApplicationEvents events;

        @Test
        void publishesOneEvent() {
            orders.place(7, "book");
            long placed = events.stream(OrderPlaced.class).count();
            System.out.println("  OrderPlaced events recorded: " + placed);
            assertThat(events.stream(OrderPlaced.class))
                    .containsExactly(new OrderPlaced(7, "book"));
        }

        @Test
        void eventsAreRecordedPerTest() {
            System.out.println("  events at the start of the next test: "
                    + events.stream(OrderPlaced.class).count());
            assertThat(events.stream(OrderPlaced.class)).isEmpty();
        }

        @Test
        void logsTheOrder(CapturedOutput output) {
            orders.place(8, "pen");
            assertThat(output).contains("order 8 placed for pen");
            System.out.println("  captured output contains the log line: "
                    + output.getOut().contains("order 8 placed for pen"));
        }
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectMethod(OrderServiceTest.class,
                                        "publishesOneEvent"),
                                DiscoverySelectors.selectMethod(OrderServiceTest.class,
                                        "eventsAreRecordedPerTest"),
                                DiscoverySelectors.selectMethod(OrderServiceTest.class,
                                        "logsTheOrder", CapturedOutput.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        if (id.isTest()) {
                            System.out.println(id.getDisplayName() + ": " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
    }
}
Output
INFO  shop.orders - order 7 placed for book
  OrderPlaced events recorded: 1
publishesOneEvent(): SUCCESSFUL
  events at the start of the next test: 0
eventsAreRecordedPerTest(): SUCCESSFUL
INFO  shop.orders - order 8 placed for pen
  captured output contains the log line: true
logsTheOrder(CapturedOutput): SUCCESSFUL
  • @RecordApplicationEvents recorded every event published in the test, and the test found exactly one OrderPlaced(7, "book"). Records make the comparison easy, because their equals compares all fields.
  • The next test saw 0 events. Recording starts afresh for each test method, so an event from one test cannot satisfy another.
  • OutputCaptureExtension captured the console while the test ran, including the log line, which appears in the output above because the extension also passes it through. CapturedOutput is injected as a test method parameter.

Assert on events when the event is part of the design, for example because other modules listen to it. Assert on log output only for messages that matter to operations, such as an audit line, since a test that checks the exact wording of ordinary log messages breaks with every reworded message.

Testing configuration with ApplicationContextRunner

Conditional configuration, the kind found in auto-configuration and shared library modules, needs many contexts: one per combination of properties and beans. ApplicationContextRunner starts a small, plain context for each combination in milliseconds, without @SpringBootTest. This mail auto-configuration is switched on by a property and backs off when the application defines its own sender:

Java
package demo.advanced.runner;

import static org.assertj.core.api.Assertions.assertThat;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class ConditionalConfig {

    interface MailSender {
        String describe();
    }

    record SmtpMailSender(String host) implements MailSender {
        public String describe() {
            return "SMTP via " + host;
        }
    }

    // the configuration under test: a library's auto-configuration
    @AutoConfiguration
    @ConditionalOnBooleanProperty("shop.mail.enabled")
    static class MailAutoConfiguration {
        @Bean
        @ConditionalOnMissingBean
        MailSender mailSender(@Value("${shop.mail.host}") String host) {
            return new SmtpMailSender(host);
        }
    }

    @Configuration
    static class CustomMailConfig {
        @Bean
        MailSender customSender() {
            return () -> "custom sender from the application";
        }
    }

    public static void main(String[] args) {
        ApplicationContextRunner runner = new ApplicationContextRunner()
                .withConfiguration(AutoConfigurations.of(MailAutoConfiguration.class));

        runner.run(context -> {
            System.out.println("Property not set: MailSender beans = "
                    + context.getBeanNamesForType(MailSender.class).length);
            assertThat(context).doesNotHaveBean(MailSender.class);
        });

        runner.withPropertyValues("shop.mail.enabled=true", "shop.mail.host=smtp.test")
                .run(context -> {
                    System.out.println("Enabled: " + context.getBean(MailSender.class).describe());
                    assertThat(context).hasSingleBean(SmtpMailSender.class);
                });

        runner.withPropertyValues("shop.mail.enabled=true", "shop.mail.host=smtp.test")
                .withUserConfiguration(CustomMailConfig.class)
                .run(context -> {
                    System.out.println("Enabled, application bean present: "
                            + context.getBean(MailSender.class).describe());
                    assertThat(context).doesNotHaveBean(SmtpMailSender.class);
                });

        // a bare runner has no placeholder support: ${...} is injected as it stands
        runner.withPropertyValues("shop.mail.enabled=true")
                .run(context -> System.out.println("Enabled, host missing, bare runner: "
                        + context.getBean(MailSender.class).describe()));

        // with the auto-configuration that every Boot application has, it fails as it should
        runner.withConfiguration(AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class))
                .withPropertyValues("shop.mail.enabled=true")
                .run(context -> {
                    assertThat(context).hasFailed();
                    Throwable root = context.getStartupFailure();
                    while (root.getCause() != null) {
                        root = root.getCause();
                    }
                    System.out.println("Enabled, host missing, with placeholders: failed: "
                            + root.getMessage());
                });
    }
}
Output
Property not set: MailSender beans = 0
Enabled: SMTP via smtp.test
Enabled, application bean present: custom sender from the application
Enabled, host missing, bare runner: SMTP via ${shop.mail.host}
Enabled, host missing, with placeholders: failed: Could not resolve placeholder 'shop.mail.host' in value "${shop.mail.host}"
  • Without shop.mail.enabled, @ConditionalOnBooleanProperty did not match and there was no MailSender.
  • With the property and a host, the auto-configuration created an SmtpMailSender for smtp.test.
  • With an application bean of the same type, @ConditionalOnMissingBean backed off and the application's sender was used. This works because AutoConfigurations.of registers the class as auto-configuration, which is processed after the user configuration.
  • With the host missing, the bare runner did not fail: it injected the text ${shop.mail.host} as the host. A plain context has no placeholder resolution unless something registers it.
  • Adding PropertyPlaceholderAutoConfiguration, which every Spring Boot application has, made the same case fail as it would in production, with "Could not resolve placeholder 'shop.mail.host'".

The fourth case is a trap worth remembering: the runner contains only what you give it. Add the auto-configurations your configuration depends on, or the test can pass on a case that fails in a real application. WebApplicationContextRunner and ReactiveWebApplicationContextRunner do the same for web configuration.

More slices: @JdbcTest

Every Spring Boot 4 technology module that has a slice ships it in its own test module. @JdbcTest, from spring-boot-jdbc-test, is the slice for code that uses JdbcTemplate or JdbcClient without JPA. It starts a data source, replaced by an embedded database, a transaction manager and the JDBC helpers, and rolls back each test like @DataJpaTest:

Java
package demo.advanced.jdbctest;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.jdbc.test.autoconfigure.JdbcTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.test.context.jdbc.Sql;

public class JdbcSlice {

    @SpringBootApplication
    static class ShopApplication {
    }

    @Repository
    static class OrderDao {
        private final JdbcClient jdbc;

        OrderDao(JdbcClient jdbc) {
            this.jdbc = jdbc;
        }

        int add(String sku, int quantity) {
            return jdbc.sql("insert into orders(sku, quantity) values (?, ?)")
                    .params(sku, quantity).update();
        }

        int totalQuantity() {
            return jdbc.sql("select coalesce(sum(quantity), 0) from orders")
                    .query(Integer.class).single();
        }
    }

    @Service
    static class ReportService {
    }

    @JdbcTest(properties = {"spring.main.banner-mode=off", "logging.level.root=WARN"})
    @Import(OrderDao.class)                     // @Repository classes are not in the slice
    @Sql(statements = "create table if not exists orders(sku varchar(20), quantity int)")
    @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
    static class OrderDaoTest {
        @Autowired
        OrderDao dao;

        @Autowired
        ApplicationContext context;

        @Test
        @Order(1)
        void addsUpQuantities() {
            dao.add("book", 2);
            dao.add("pen", 5);
            System.out.println("  total after two inserts: " + dao.totalQuantity());
            assertThat(dao.totalQuantity()).isEqualTo(7);
        }

        @Test
        @Order(2)
        void startsEmptyAgain() {
            System.out.println("  total in the next test: " + dao.totalQuantity());
            assertThat(dao.totalQuantity()).isZero();
        }

        @Test
        @Order(3)
        void loadsOnlyJdbc() {
            System.out.println("  OrderDao beans: "
                    + context.getBeanNamesForType(OrderDao.class).length
                    + ", ReportService beans: "
                    + context.getBeanNamesForType(ReportService.class).length
                    + ", beans in total: " + context.getBeanDefinitionCount());
        }
    }

    public static void main(String[] args) {
        LauncherFactory.create().execute(
                LauncherDiscoveryRequestBuilder.request()
                        .selectors(DiscoverySelectors.selectClass(OrderDaoTest.class))
                        .build(),
                new TestExecutionListener() {
                    @Override
                    public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                        if (id.isTest()) {
                            System.out.println(id.getDisplayName() + ": " + result.getStatus());
                            result.getThrowable().ifPresent(t -> System.out.println("  " + t));
                        }
                    }
                });
    }
}
Output
total after two inserts: 7
addsUpQuantities(): SUCCESSFUL
  total in the next test: 0
startsEmptyAgain(): SUCCESSFUL
  OrderDao beans: 1, ReportService beans: 0, beans in total: 58
loadsOnlyJdbc(): SUCCESSFUL
  • The first test inserted two rows and read a total of 7. The second test read 0: the inserts were rolled back when the first test ended.
  • The @Sql statement ran before each test. It uses if not exists because the table, a DDL change, is not rolled back.
  • OrderDao is in the context only because of @Import: @JdbcTest does not scan @Repository classes. ReportService was left out, and the slice had 58 beans.
Spring Boot 4 slice annotations and their modules
AnnotationModuleWhat it loads
@WebMvcTestspring-boot-webmvc-testControllers, advice, filters, MVC configuration, MockMvc
@WebFluxTestspring-boot-webflux-testWebFlux controllers and WebTestClient
@DataJpaTestspring-boot-data-jpa-testEntities, repositories, embedded database, TestEntityManager
@JdbcTestspring-boot-jdbc-testData source, JdbcTemplate, JdbcClient, transactions
@RestClientTestspring-boot-restclient-testRestClient.Builder, Jackson, MockRestServiceServer
@JsonTestspring-boot-test-autoconfigureJackson and the JSON testers

Keeping a large suite fast

  • Few distinct configurations: put the common @SpringBootTest setup, including the usual @MockitoBean fields, in one abstract base class, so most classes share one cached context.
  • No routine @DirtiesContext: every use closes a context that the next class has to start again. Reset state with @Sql or a cleanup method instead, and keep @DirtiesContext for tests that really break the context.
  • Slices and runners first: a @WebMvcTest or an ApplicationContextRunner starts a fraction of the beans, and a plain unit test starts none.
  • Watch the cache: DEBUG logging for org.springframework.test.context.cache shows hits, misses and the cache size.
  • Fail fast: a context that fails to start is remembered, and later classes with the same configuration fail at once instead of retrying the start. The failure threshold is 1 by default and is set with spring.test.context.failure.threshold.

Choosing the right mechanism

Which test mechanism to use for which need
NeedMechanism
Replace a bean with a mock@MockitoBean
Replace a bean with a real object, such as a fixed Clock@TestBean with a static factory method
Add a bean that only tests needNested @TestConfiguration, never plain @Configuration
A property fixed for one test class@SpringBootTest(properties = ...) or @TestPropertySource
A property known only at run time@DynamicPropertySource
Database tests that leave no data behind@Transactional test methods, with @Sql for test data
Code that calls another serviceMockRestServiceServer, or @RestClientTest
A published event or a log line@RecordApplicationEvents, OutputCaptureExtension
Conditional configuration or auto-configurationApplicationContextRunner

The basics of @SpringBootTest, MockMvc and slices are on the Spring Boot testing page, and tests against real databases and brokers on the Testcontainers page.