Sub topic 15
Keeping the test suite fast and reliable
This chapter assumes you can write unit, slice, and @SpringBootTest tests, and that you know the test context cache reuses a started application context between test classes. Here you apply that knowledge to keep a growing suite quick and trustworthy.
Where the time goes
Most of the time in a Spring Boot suite goes to starting contexts and containers, not to running assertions. A plain unit test takes milliseconds. A slice test takes about a second. A full context with a database container can take many seconds. The suite stays fast if you start each expensive thing as few times as possible.
Keep the number of contexts small
Every distinct combination of configuration creates a new cached context. Each of these changes the cache key:
- A different set of
@MockitoBeandeclarations - A different
@ActiveProfilesvalue - A different
@TestPropertySourceor@TestConfiguration @DirtiesContext, which discards the context after the test
To reduce the count, put common configuration in one place and let full-context tests share it. Avoid @DirtiesContext unless a test really corrupts the context. Clean data instead.
Share containers
Starting a PostgreSQL container for every test class is slow. Declare the container once as a bean in a shared configuration class. The container then starts once per context, and the cache reuses that context.
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");
}
}Test classes add @Import(ContainersConfig.class). Because the imports match, they share one context and one container.
Keep tests independent
Flaky tests usually come from shared state or timing. Use these rules:
- Each test creates the data it needs and does not rely on test order.
@DataJpaTestrolls back each test's transaction automatically.- A
RANDOM_PORTtest runs the server on another thread, so the test's transaction cannot roll back the server's work. Delete the data in@AfterEach, or use unique values such as random names. - Never use fixed ports. Use
RANDOM_PORT. - Never use
Thread.sleep. Wait for a condition with Awaitility, whichspring-boot-starter-testalready includes.
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
class AsyncWaitTest {
@Test
void waitsForConditionInsteadOfSleeping() {
AtomicBoolean done = new AtomicBoolean(false);
new Thread(() -> done.set(true)).start();
await().atMost(Duration.ofSeconds(2)).untilAsserted(() ->
assertThat(done).isTrue());
}
}The test passes as soon as the condition holds, and it fails with a clear message after the timeout.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Suite slows down after adding a test | New `@MockitoBean` or profile created another context | Reuse the shared configuration |
| Test passes alone, fails in the suite | Leftover data from an earlier test | Clean up or use unique data |
| Intermittent failures | Fixed sleeps or asynchronous work | Use Awaitility |
| Container starts many times | Container declared per class | Declare it once in a shared configuration |
Habits worth keeping
- Put most tests at the unit and slice levels, and keep few full-context tests.
- Run the whole suite in CI, and run slices and unit tests locally for fast feedback.
- Treat a flaky test as a bug. Fix or remove it, because a suite people re-run until it passes stops being trusted.
Exercise
Two @SpringBootTest classes are identical except that one adds a single @MockitoBean. What happens to startup cost, and how can you avoid it?
Show answer
The extra mock changes the context cache key, so Spring starts a second context. To avoid it, declare the same mocks in both classes, move the shared mock into a common configuration, or test that class with a slice or plain unit test that does not need the full context.