Sub topic 15
Keeping the test suite fast and reliable
This chapter assumes you have read the earlier chapters on @SpringBootTest, test slices, @MockitoBean, Testcontainers, and context caching. You should be able to write each kind of test already. The question here is how to keep a few hundred of them quick to run and trustworthy. A slow suite gets run less often. A flaky suite (one that sometimes fails with no code change) teaches the team to ignore red builds.
Where the time goes
Most of the time in a Spring Boot suite goes to three things:
- Starting application contexts. A full context can take several seconds, and a slice context takes about one.
- Starting infrastructure, such as a PostgreSQL container, which takes several seconds each time.
- Waiting:
Thread.sleep, retries, and timeouts.
Plain unit tests cost milliseconds. A suite stays fast when the many cheap tests do most of the work and the expensive ones are shared or rare.
Keep the pyramid shape
Choose the cheapest test that can fail for the reason you care about.
| Question you are asking | Cheapest useful test |
|---|---|
| Does this business rule compute correctly? | Plain JUnit and Mockito unit test |
| Does the URL map, validate, and serialize correctly? | `@WebMvcTest` |
| Does this query return the right rows? | `@DataJpaTest` with a real database |
| Do the layers work together with real configuration? | A few `@SpringBootTest` tests |
A common failure is using @SpringBootTest for everything because it is the first annotation people learn. Every one of those tests pays the context cost, and each failure points at the whole application instead of one layer.
Make the context cache work for you
Spring caches an application context and reuses it for every test class with the same configuration. The cache key includes:
- the
@ContextConfigurationclasses and any@Imported configuration - active profiles from
@ActiveProfiles @TestPropertySourceand@SpringBootTest(properties = ...)values- the set of
@MockitoBeanand@MockitoSpyBeanoverrides - the web environment mode
Any difference creates a new context. The diagram shows four test classes that end up with three contexts.
Find out how many contexts you create
Turn on cache logging in src/test/resources/application.properties:
logging.level.org.springframework.test.context.cache=DEBUGThe log reports each hit and miss, along with the cache size. If the number of misses is close to the number of test classes, nothing is being shared.
Reduce the number of distinct contexts
- Put the
@MockitoBeandeclarations that many tests need into one shared abstract base class or one@TestConfiguration. Declaring a mock in only some test classes multiplies contexts. - Use one small set of profiles and properties for integration tests. Don't give each class its own
@TestPropertySourceunless it needs one. - Avoid
@DirtiesContext. It evicts the context after the test, so the next class must rebuild it. Reset state in the test itself, for example by clearing tables or callingreseton a mock. - The cache holds 32 contexts by default and evicts the least recently used. Raise it with
spring.test.context.cache.maxSizeonly if you cannot reduce the variety.
Share one database container
A static field annotated with @Container starts a new container for each test class. If each class has its own, a ten-class suite starts ten databases. Declare the container once as a bean in a shared test configuration. The container then lives as long as the cached context, so every test class that reuses the context reuses the container too.
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.containers.PostgreSQLContainer;
@TestConfiguration(proxyBeanMethods = false)
public class ContainersConfig {
@Bean
@ServiceConnection
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>("postgres:16");
}
}Each test imports it:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Import;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(ContainersConfig.class)
class GreetingRepositoryTest {
@Autowired
GreetingRepository repository;
@Test
void findsGreetingByName() {
repository.save(new Greeting("Ada", "Hello, Ada"));
assertThat(repository.findByName("Ada")).isPresent();
}
}This requires Spring Boot 3.1 or later and the spring-boot-testcontainers dependency. Slice tests and full-context tests that import the same configuration still get separate contexts, but those contexts can each reuse a container only within their own cache entry. To share one database across slice and full contexts, use a singleton container started in a static initializer instead and expose it with @DynamicPropertySource.
Isolate test data
Tests that share a database must not depend on each other's leftovers. Three mechanisms cover most cases:
@DataJpaTestand other@Transactionaltests roll back after each method. This is the cheapest option.- With
webEnvironment = RANDOM_PORT, the server handles requests on its own threads. A@Transactionalannotation on the test method does not wrap them, so nothing rolls back. Delete the rows you created in an@AfterEachmethod, or truncate tables in@BeforeEach. - Create unique data per test, such as a random name or UUID, so tests don't collide even if cleanup fails.
Remove the common causes of flakiness
A flaky test has a hidden input: time, ordering, shared state, or concurrency.
Time
Inject a java.time.Clock instead of calling Instant.now() inside the service. Tests then control the time.
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class TokenService {
private final Clock clock;
TokenService(Clock clock) {
this.clock = clock;
}
boolean isExpired(Instant expiresAt) {
return clock.instant().isAfter(expiresAt);
}
}
class TokenServiceTest {
private final Clock fixed = Clock.fixed(Instant.parse("2026-12-01T10:00:00Z"), ZoneOffset.UTC);
private final TokenService service = new TokenService(fixed);
@Test
void tokenInThePastIsExpired() {
assertThat(service.isExpired(Instant.parse("2026-12-01T09:59:59Z"))).isTrue();
}
@Test
void tokenInTheFutureIsValid() {
assertThat(service.isExpired(Instant.parse("2026-12-01T10:00:01Z"))).isFalse();
}
}In the application, expose a Clock bean with Clock.systemUTC(). In a Spring test, replace it with a fixed one through @TestConfiguration.
Asynchronous work
Thread.sleep(2000) is both too slow when the work finishes early and too short on a slow CI machine. Awaitility is included in spring-boot-starter-test. It polls until a condition holds and fails after a timeout.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
class AsyncCounterTest {
@Test
void counterIsUpdatedEventually() {
AtomicInteger counter = new AtomicInteger();
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.submit(counter::incrementAndGet);
await().atMost(Duration.ofSeconds(5))
.untilAsserted(() -> assertThat(counter.get()).isEqualTo(1));
} finally {
executor.shutdown();
}
}
}Ordering and shared state
Every test must pass alone and in any order. Watch for static mutable fields, singleton beans that hold state in a cached context, and mocks that keep stubbing across tests. @MockitoBean mocks are reset after each test by default, but hand-built mocks held in static fields are not. Run a single test class on its own now and then. If it fails alone but passes in the suite, it depends on another test.
Ports and external services
Use RANDOM_PORT and never a fixed port. Don't call real third-party services from tests. Use @RestClientTest with MockRestServiceServer, or a stub server, so a remote outage can't turn your build red.
Split the suite by cost
Tag the expensive tests so developers can run only the cheap ones locally and CI can run everything.
import org.junit.jupiter.api.Tag;
import org.springframework.boot.test.context.SpringBootTest;
@Tag("integration")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class GreetingApiTest {
// tests that call the running application
}This Gradle configuration keeps test fast and adds an integrationTest task:
tasks.named('test') {
useJUnitPlatform {
excludeTags 'integration'
}
}
tasks.register('integrationTest', Test) {
description = 'Runs tests tagged integration'
group = 'verification'
testClassesDirs = sourceSets.test.output.classesDirs
classpath = sourceSets.test.runtimeClasspath
useJUnitPlatform {
includeTags 'integration'
}
shouldRunAfter tasks.named('test')
}
tasks.named('check') {
dependsOn tasks.named('integrationTest')
}With this setup ./gradlew test runs only the fast tests, and ./gradlew check runs both groups. In Maven, Surefire and Failsafe provide the same split.
Parallelism and its limits
There are two ways to run tests in parallel, and they have different costs.
| Approach | How to enable | Cost and risk |
|---|---|---|
| Several JVMs | `maxParallelForks = 2` in the Gradle `test` task | Each JVM has its own context cache and its own containers. Memory use rises. Tests stay isolated from each other. |
| Threads inside one JVM | `junit.jupiter.execution.parallel.enabled = true` in `src/test/resources/junit-platform.properties` | Tests share the cached contexts and any static state. Shared databases and mutable beans cause races. |
For unit tests with no shared state, JUnit's thread-level parallelism is safe and effective. For Spring integration tests that share a database, it is usually not. Start with forks, keep integration tests sequential, and measure before and after. If the suite is slow because of a handful of context starts, parallelism only moves the cost around.
A review checklist
- Does each test use the lowest level that can catch the bug?
- How many context cache misses does the log show, and can they be merged?
- Is
@DirtiesContextused anywhere, and could explicit cleanup replace it? - Is the database container created once per context rather than once per class?
- Does any test use
Thread.sleep, the system clock, a fixed port, or a real external service? - Does every test pass when run alone?
Exercise
A suite has eight @SpringBootTest classes. Four of them each declare @MockitoBean EmailSender emailSender, and the other four declare nothing. The cache log shows two contexts being created. A teammate then adds @MockitoBean PaymentGateway gateway to two of the four classes that mock EmailSender. How many contexts are created now, and how would you bring the number back down?
Show answer
Three contexts. One serves the four classes with no mocks, one serves the two classes that mock only EmailSender, and one serves the two classes that mock both beans. Because the set of mock beans is part of the cache key, each distinct set creates its own context. To reduce the count, move the shared mocks into a common base class or @TestConfiguration so that all eight classes use the same set, or drop the mocks from classes that don't need them.
Exercise
A @SpringBootTest(webEnvironment = RANDOM_PORT) test is annotated with @Transactional. It saves a Greeting through TestRestTemplate with a POST request. The next test expects an empty table but finds the row. Why did the rollback not happen, and what should the first test do?
Show answer
The HTTP request is handled by a server thread, which runs outside the test's transaction. The service commits its own transaction, so the test's rollback cannot undo it. The first test should delete the row it created in an @AfterEach method, or the suite should truncate the tables in @BeforeEach. Using unique data per test also prevents collisions.