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 Context caching, measured Replacing and adding beans Test properties and which one wins Transactional tests and what they roll back Testing calls to other services Asserting events and log output Testing configuration with ApplicationContextRunner More slices: @JdbcTest Keeping a large suite fast Choosing the right mechanism
What the TestContext framework does for each test
Every Spring test, whether it uses @SpringBootTest@ContextConfiguration
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
| Feature | From | Since | What it is for |
|---|---|---|---|
| Context cache | Spring Framework | 2.5 | Starting each distinct configuration only once |
| Context pausing | Spring Framework | 7.0 | Stopping background work in cached contexts not in use |
@TestBean | Spring Framework | 6.2 | Replacing a bean with one built by a factory method |
@TestConfiguration | Spring Boot | 1.4 | Adding beans to the application's configuration in a test |
@DynamicPropertySource | Spring Framework | 5.2.5 | Properties whose values are known only at run time |
@Sql@Commit@AfterTransaction | Spring Framework | 2.5 to 4.2 | Test data and test transactions |
MockRestServiceServer | Spring Framework | 3.2; RestClient | Testing code that calls other services |
@RecordApplicationEvents | Spring Framework | 5.3.3 | Asserting on published application events |
OutputCaptureExtension | Spring Boot | 2.2 | Asserting on console and log output |
ApplicationContextRunner | Spring Boot | 2.0 | Testing configuration and auto-configuration quickly |
All programs run with Spring Boot 4.1 and JUnit 6. As on the mainlogback-test.xmlWARNsrc/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:
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");
}
}
OrderTest context #1
InvoiceTest context #1
MailMockTest context #2
EuProfileTest context #3
DirtyTest context #1
AfterDirtyTest context #4
Six test classes started 4 contexts
started context 1, andOrderTest , with the same configuration, reused it. That reuse is the whole point of the cache.InvoiceTest added oneMailMockTest , and got context 2. Bean overrides are part of the cache key, because a context with a mock in it is a different context.@MockitoBean activated a profile and got context 3. Profiles, test properties andEuProfileTest methods are part of the key too.@DynamicPropertySource had the same configuration as the first two, so it reused context 1. ItsDirtyTest then closed that context after the class finished.@DirtiesContext 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 withoutAfterDirtyTest and with fewer distinct overrides would have cost two.@DirtiesContext
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.maxSizelogging.level.org.springframework.test.context.cache=DEBUG
Replacing and adding beans
An invoice service that computes a due date from Clock
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));
}
}
});
}
}
(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 replaced the@TestBean 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 toclock .dueDate() : the nestedRecordingAuditTest was added to the application's configuration and its@TestConfiguration 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 itsauditSink .entries : a nested class annotated with plainNestedConfigurationTest was used instead of the application. The context had no@Configuration at all, and in a real test everyInvoiceService application bean would fail.@Autowired
The second test needs spring.main.allow-bean-definition-overriding=trueBeanDefinitionOverrideException@TestBean@MockitoBean@TestConfiguration
Test properties and which one wins
A test can set properties in three places: the properties@SpringBootTest@TestPropertySource@DynamicPropertySource
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));
}
}
});
}
}
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
appears only ina , and that value was used. These properties already beat@SpringBootTest and environment variables.application.properties - Key
was set by bothb and@SpringBootTest , and@TestPropertySource won.@TestPropertySource - Keys
andc show thatd beat both of the others. It has the highest precedence of all test property sources.@DynamicPropertySource
@DynamicPropertySourceSupplierDynamicPropertyRegistrar
Transactional tests and what they roll back
A test method annotated with @Transactional@Sql
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));
}
}
});
}
}
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)
: the insert was visible inside the test, 1 row, androlledBackByDefault was true.TestTransaction.isActive() ran after the rollback and found 0 rows.@AfterTransaction :committedWithCommit 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.@Commit :sqlRunsInsideTheTestTransaction inserted two rows before the test method, inside its transaction. The test saw 3 rows, and afterwards they were rolled back to 1.@Sql : the service method ran withrequiresNewEscapesTheRollback , so it committed in its own transaction before returning. The test's rollback could not undo it, and the table ended with 2 rows.REQUIRES_NEW
The rollback covers only work done in the test's own transaction, on the test's thread. Writes made with REQUIRES_NEW@AsyncRANDOM_PORT@SqlexecutionPhase = AFTER_TEST_METHOD@TransactionalEventListener
Testing calls to other services
Code that calls another service through RestClientMockRestServiceServerRestClient.Builder
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));
}
}
});
}
}
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
header, returned JSON, and the client turned it into the rateAccept .1.0842 fails if an expected request was never made.server.verify() - The 503 response surfaced as
, the specific subclass, with the messageHttpServerErrorException.ServiceUnavailable . That is the exception a retry or circuit breaker would be configured for.503 Service Unavailable: [no body] - The third test expected a request for EUR to USD and received one for USD to JPY. The mock server threw an
at once, naming both URLs.AssertionError
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@RestClientTestspring-boot-restclient-testMockRestServiceServer
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));
}
}
});
}
}
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
intoquoted_on . Its builder came from the context, soquotedOn=2026-03-09 applied to it, as it would in the running application.spring.jackson.property-naming-strategy=SNAKE_CASE - The same client built from
gotRestClient.builder() : 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.quotedOn=null - The third test set its own expectation and passed, although the first test had used the server too. Spring Boot resets the
bean after each test.MockRestServiceServer - The slice held the
named inRateClient , nocomponents , and 51 beans in total.InvoiceService
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:
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));
}
}
});
}
}
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
recorded every event published in the test, and the test found exactly one@RecordApplicationEvents . Records make the comparison easy, because theirOrderPlaced(7, "book") compares all fields.equals- The next test saw 0 events. Recording starts afresh for each test method, so an event from one test cannot satisfy another.
captured the console while the test ran, including the log line, which appears in the output above because the extension also passes it through.OutputCaptureExtension is injected as a test method parameter.CapturedOutput
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@SpringBootTest
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());
});
}
}
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 did not match and there was no@ConditionalOnBooleanProperty .MailSender - With the property and a host, the auto-configuration created an
forSmtpMailSender .smtp.test - With an application bean of the same type,
backed off and the application's sender was used. This works because@ConditionalOnMissingBean registers the class as auto-configuration, which is processed after the user configuration.AutoConfigurations.of - With the host missing, the bare runner did not fail: it injected the text
as the host. A plain context has no placeholder resolution unless something registers it.${shop.mail.host} - Adding
, which every Spring Boot application has, made the same case fail as it would in production, with "Could not resolve placeholder 'shop.mail.host'".PropertyPlaceholderAutoConfiguration
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. WebApplicationContextRunnerReactiveWebApplicationContextRunner
More slices: @JdbcTest
Every Spring Boot 4 technology module that has a slice ships it in its own test module. @JdbcTestspring-boot-jdbc-testJdbcTemplateJdbcClient@DataJpaTest
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));
}
}
});
}
}
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
statement ran before each test. It uses@Sql because the table, a DDL change, is not rolled back.if not exists is in the context only because ofOrderDao :@Import does not scan@JdbcTest classes.@Repository was left out, and the slice had 58 beans.ReportService
| Annotation | Module | What it loads |
|---|---|---|
@WebMvcTest | spring-boot-webmvc-test | Controllers, advice, filters, MVC configuration, MockMvc |
@WebFluxTest | spring-boot-webflux-test | WebFlux controllers and WebTestClient |
@DataJpaTest | spring-boot-data-jpa-test | Entities, repositories, embedded database, TestEntityManager |
@JdbcTest | spring-boot-jdbc-test | Data source, JdbcTemplateJdbcClient |
@RestClientTest | spring-boot-restclient-test | RestClient.BuilderMockRestServiceServer |
@JsonTest | spring-boot-test-autoconfigure | Jackson and the JSON testers |
Keeping a large suite fast
- Few distinct configurations: put the common
setup, including the usual@SpringBootTest fields, in one abstract base class, so most classes share one cached context.@MockitoBean - No routine @DirtiesContext: every use closes a context that the next class has to start again. Reset state with
or a cleanup method instead, and keep@Sql for tests that really break the context.@DirtiesContext - Slices and runners first: a
or an@WebMvcTest starts a fraction of the beans, and a plain unit test starts none.ApplicationContextRunner - Watch the cache: DEBUG logging for
shows hits, misses and the cache size.org.springframework.test.context.cache - 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
| Need | Mechanism |
|---|---|
| Replace a bean with a mock | @MockitoBean |
Replace a bean with a real object, such as a fixed Clock | @TestBean |
| Add a bean that only tests need | Nested @TestConfiguration@Configuration |
| A property fixed for one test class | @SpringBootTest(properties = ...)@TestPropertySource |
| A property known only at run time | @DynamicPropertySource |
| Database tests that leave no data behind | @Transactional@Sql |
| Code that calls another service | MockRestServiceServer@RestClientTest |
| A published event or a log line | @RecordApplicationEventsOutputCaptureExtension |
| Conditional configuration or auto-configuration | ApplicationContextRunner |
The basics of @SpringBootTest