Quick revision
The short answer
We first measure how many distinct application contexts the build creates, because every different set of @MockitoBean overrides, properties and profiles starts a new one. Then we standardise a few shared test base configurations so contexts come from the cache, move logic tests to plain unit tests and web tests to slices such as @WebMvcTest, remove unneeded @DirtiesContext, and finally run in parallel forks on CI with Testcontainers containers shared across tests.
What to remember
In this answer, we started by measuring context creation with the TestContext cache statistics, then cut the number of distinct contexts with a few shared base configurations, moved logic tests to unit tests and web and persistence tests to slices, removed @DirtiesContext where state could be reset directly, and only then parallelised CI forks and shared containers. Each step keeps the same confidence while removing repeated startup cost.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We first measure how many distinct application contexts the build creates, because every different set of @MockitoBean overrides, properties and profiles starts a new one. Then we standardise a few shared test base configurations so contexts come from the cache, move logic tests to plain unit tests and web tests to slices such as @WebMvcTest, remove unneeded @DirtiesContext, and finally run in parallel forks on CI with Testcontainers containers shared across tests.
Why this question is asked
A 25 minute build changes how a team works: people batch changes, skip running tests locally and wait for CI, and feedback on a mistake arrives after they have moved on. Usually the cause is not that 600 tests are too many, but that each one pays for an expensive startup over and over. Interviewers ask this to see whether we measure before optimising and whether we know how Spring's test context cache works. In this answer, we will recap the cache, measure the problem, and then apply the fixes in the order that usually saves the most time.
1A Quick Recap of the Context Cache
Starting a Spring Boot application context for a test takes time: scanning, auto-configuration, connection pools, maybe Flyway migrations. For a mid-sized service that is often 5 to 15 seconds. To avoid paying it for every test class, the Spring TestContext framework keeps started contexts in a cache inside the JVM and reuses one whenever a new test class has exactly the same configuration.
The key of that cache is the merged configuration of the test class: configuration classes, active profiles, test properties, context customizers such as bean overrides, and so on. Any difference, even one extra @MockitoBean field, means a different key and a fresh context. So 600 test classes might share 3 contexts, or need 150.
2Measure How Many Contexts We Create
Before changing anything, we find out where the time goes. The TestContext framework logs cache statistics when we turn on debug logging for its cache category.
Notice the numbers in this example. 190 misses means 190 context starts; at 6 seconds each, that is 19 of the 25 minutes. A size stuck at the maximum of 32 means contexts are also being evicted and rebuilt. Together with the build tool's report of the slowest test classes, this tells us exactly which configurations to merge.
3Standardise a Few Shared Base Configurations
Most extra contexts come from small, accidental differences: one class mocks EmailSender, another mocks EmailSender and SmsSender, a third adds a property. We give the team two or three base classes and ask test classes to extend one instead of declaring their own variations.
| Difference between two classes | Same context? |
|---|---|
| Same base class, different test methods | Yes |
One extra @MockitoBean field | No |
Different @ActiveProfiles | No |
Different @TestPropertySource or properties attribute | No |
@DirtiesContext on one of them | No, the context is thrown away |
Mocking a bean a test does not use costs almost nothing, while a different mock set costs a whole startup. So sharing a slightly larger, fixed mock set is the right trade.
4Push Tests Down to Cheaper Kinds
Many of the 600 tests probably check logic, such as price calculation or validation rules, through a full context. Those become plain unit tests with JUnit and Mockito: no Spring at all, milliseconds each. Controller tests that only need the web layer move to @WebMvcTest, and repository tests to @DataJpaTest. Slices still start a context, but a much smaller one, and slices of the same kind share cached contexts too.
The aim is not to remove integration tests. We keep a focused set of @SpringBootTest classes that prove the pieces work together, and stop using the full context as the default for every test.
5Remove Unneeded @DirtiesContext
@DirtiesContext tells Spring to close the context after the class or method, so the next test builds a new one. Teams often add it to fix a flaky test caused by shared state, and then it stays forever. Each use costs a full startup, sometimes per method. We search for it, find out what state it was protecting, such as a cache or an in-memory flag, and reset that state directly in a @BeforeEach or @AfterEach instead.
6Parallel Forks and Shared Containers
Once each JVM reuses contexts well, we split the suite across parallel forks on CI, for example four forks with Gradle's maxParallelForks or Surefire's forkCount. Each fork has its own cache, so this works best after the earlier steps have reduced the number of configurations. For containers, a database started once per JVM and shared through a static field or a shared configuration class, rather than one per test class, removes several seconds per class.
- Measurecache hits, misses, slowest classes
- Merge configurationsshared base classes, same mocks
- Push tests downunit tests and slices
- Remove @DirtiesContextreset state directly
- Paralleliseforks on CI, shared containers
- Measure againkeep a build-time budget
6 steps in order. Play them, or step through them one at a time.
7Follow-up questions
Why not just run everything in parallel first?
Parallel forks multiply the context problem: each fork rebuilds the same 190 contexts in its own JVM, so we use four times the memory and database connections and save less than expected. Reducing distinct contexts first makes parallelism pay off.
Will moving tests to unit tests lower confidence?
Not if we move the right ones. A rule like a discount calculation is tested more thoroughly by fast unit tests that try many inputs. Wiring, security, persistence and serialization still get integration tests, which is where those bugs appear.
How do I stop the build from getting slow again?
Keep the cache statistics in the CI log, set a build-time budget, and treat a new context configuration as something to justify in review, just like a new dependency.
8Conclusion
In this answer, we started by measuring context creation with the TestContext cache statistics, then cut the number of distinct contexts with a few shared base configurations, moved logic tests to unit tests and web and persistence tests to slices, removed @DirtiesContext where state could be reset directly, and only then parallelised CI forks and shared containers. Each step keeps the same confidence while removing repeated startup cost.
Open with
I would start by measuring, because the usual cause is not 600 tests but how many application contexts they create. I would turn on debug logging for org.springframework.test.context.cache, which prints hit and miss counts, and look at the slowest test classes.
Then, if they want more
If I see something like 190 misses at six seconds each, that is most of the 25 minutes. Every different combination of @MockitoBean fields, profiles or properties is a new context, so I would standardise two or three base test classes with a fixed set of mocks and profiles, so classes hit the cache.
Next, I would move tests that only check logic to plain unit tests, and web-only tests to @WebMvcTest and repository tests to @DataJpaTest, keeping a smaller set of real @SpringBootTest integration tests. I would search for @DirtiesContext, which throws a context away, and replace it with resetting the specific state it was protecting.
Only after that would I run the suite in parallel forks on CI and share Testcontainers containers per JVM instead of per class. Then I would keep the cache statistics and a build-time budget in CI so it does not drift back.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Boot reference, Testing
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Your service has 600 tests annotated with @SpringBootTest and the build takes 25...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/9d4720fa80/