Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

CI test time grew from 10 to 40 minutes as the Spring Boot test suite grew. How do you find where time goes and reduce it?

First measure per-test-class time, because a small fraction of classes usually takes most of the time. In Spring Boot suites the biggest cause is often the test context cache: many distinct combinations of @MockitoBean, properties or profiles force Spring to start new application contexts again and again. Then share Testcontainers across classes with a singleton pattern, run tests in parallel forks or split them across CI agents by timing data, and replace full @SpringBootTest with slice tests or plain unit tests where possible.

Why this question is asked

A test suite that grows from 10 to 40 minutes does not just waste CI money. Developers stop running the suite before pushing, pull requests wait longer, and changes get batched into bigger, riskier merges. Spring Boot suites have a characteristic way of getting slow that is easy to fix once seen. Interviewers ask this to see whether we measure before guessing and know Spring's testing internals. In this answer, we will find where the time goes, understand the context cache and how it gets defeated, share containers, parallelise, and choose cheaper kinds of tests.

1Measure Time per Test Class

The first step is data. Surefire and Failsafe write XML reports with the time of every test class and method, and most CI systems can display them, or a short script can sort them. The result is nearly always skewed: in a suite of 1,200 test classes, perhaps 60 classes take 70 percent of the time. Those are the ones to look at.

It also helps to check how many times Spring starts. Each application context start logs the Spring Boot banner or a Started ... in N seconds line, and Spring's test framework can log its context cache statistics. If a suite with 300 @SpringBootTest classes starts 120 contexts at 6 seconds each, that alone is 12 minutes.

Properties
# application.properties for tests, or a system property
logging.level.org.springframework.test.context.cache=DEBUG
# the log then reports, for example:
# Spring test ApplicationContext cache statistics: [DefaultContextCache@5b1f size = 32,
# maxSize = 32, parentContextCount = 0, hitCount = 410, missCount = 118]

A missCount of 118 means 118 context starts. Notice also size = 32 = maxSize: the cache is full, so older contexts are being evicted and may be started again later. The exact log wording may vary by Spring version.

2How the Spring Test Context Cache Works

Starting a Spring application context is expensive, often several seconds for a real service. So Spring's TestContext framework caches contexts and reuses one across all test classes that have exactly the same configuration. The cache key includes the configuration classes, active profiles, property sources such as @TestPropertySource and properties on @SpringBootTest, context customisers, and the set of beans replaced by @MockitoBean or @MockitoSpyBean, which in Spring Framework 6.2 and later replace Spring Boot's deprecated @MockBean.

So every unique combination is a new context. If one test class mocks PaymentClient, another mocks PaymentClient and EmailSender, and a third sets one extra property, that is three contexts, each started from scratch. As a suite grows, these small variations multiply, and the cache, which holds 32 contexts by default, also starts evicting.

Java
@SpringBootTest
class OrderServiceTest {
@MockitoBean PaymentClient payments; // context A
}
@SpringBootTest(properties = "shop.discounts.enabled=true")
class DiscountTest {
@MockitoBean PaymentClient payments; // context B: different properties
}
@SpringBootTest
class NotificationTest {
@MockitoBean PaymentClient payments;
@MockitoBean EmailSender email; // context C: different mocks
}
Step throughWhy a test class starts a new context
  1. Test class needs a context@SpringBootTest
  2. Build the cache keyconfig, profiles, properties, @MockitoBean set
  3. Same key in the cache?
    YesReuse it: no startup costNoStart a new context: several seconds
  4. Cache full (32 by default)?
    YesEvict the oldest contextNoKeep it for later classes

4 steps in order. Play them, or step through them one at a time.

Every unique combination of mocks and properties pays the full startup cost.

The fix is to standardise. A shared abstract base class, or a custom annotation, declares one agreed set of mocks and properties that most integration tests use, so they all hit the same cached context. Tests that truly need different configuration are grouped, rather than each having a unique variation. Avoid @DirtiesContext unless a test really corrupts the context, because it throws the cached context away.

3Share Testcontainers Across Test Classes

The second common cost is containers. If each test class declares its own @Container field, Testcontainers starts a fresh PostgreSQL or Kafka for every class, perhaps 5 to 15 seconds each. A singleton container is started once per JVM and reused by every class.

Java
abstract class IntegrationTestBase {
static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:17");
static { POSTGRES.start(); } // once per JVM, stopped by Ryuk at exit
@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", POSTGRES::getJdbcUrl);
r.add("spring.datasource.username", POSTGRES::getUsername);
r.add("spring.datasource.password", POSTGRES::getPassword);
}
}

Because the property values are the same for all subclasses, this also keeps the Spring context cache key the same. Spring Boot's @ServiceConnection on a container bean in a shared @TestConfiguration is a neater alternative that configures the connection automatically. Tests then need to clean up their own data, for example by truncating tables, instead of relying on a fresh database.

4Run Tests in Parallel and Split Across Agents

Once each test is efficient, we use more hardware. Surefire's forkCount, for example forkCount=1C for one JVM per core, runs test classes in several JVMs at once. Each fork has its own context cache and its own singleton containers, so forks only pay off once the cache is healthy; four forks with 100 contexts each are still slow. JUnit's own parallel execution within one JVM is another option, but Spring tests sharing a context must then be safe to run concurrently.

Across machines, CI can split the suite into shards, each running a subset of test classes on its own agent. The best splits use timing data from previous runs so that each shard takes about the same time; a naive split by name can leave one shard with all the slow classes.

5Use Cheaper Kinds of Tests

Finally, many slow tests do not need the whole application. A test of a controller's JSON mapping and validation can use @WebMvcTest, which starts only the web layer; a repository test can use @DataJpaTest, which starts only JPA with the data source; and logic that does not need Spring at all is best tested as a plain unit test with objects created by hand. These slice tests start in a fraction of the time and fail for clearer reasons. A healthy suite has many unit tests, a reasonable number of slice tests, and a small number of full @SpringBootTest tests for the important flows.

Where the 30 extra minutes typically go, and the fix
CauseTypical costFix
118 distinct Spring contextsabout 12 minshared base config, fewer @MockitoBean variants
Container per test classabout 8 minsingleton containers or @ServiceConnection
Everything in one JVM on one agentabout 6 minforks and timing-based shards
@SpringBootTest for simple logicabout 4 minslice tests and plain unit tests
Illustrative numbers; measuring the real suite tells us which row is biggest.

6Follow-up questions

Can we make the context cache bigger?

Yes, with the spring.test.context.cache.maxSize property, as a system property or in a spring.properties file. That helps when evictions cause restarts, but each cached context holds memory and threads, and too many can exhaust the fork's heap. Reducing the number of distinct contexts is the real fix.

Is @MockitoBean always bad for speed?

No. It is only expensive when different test classes use different sets of mocked beans, because each set is a new context. If many classes use the same set, they share one context. Putting the common mocks in a shared base class keeps the benefit.

How do we stop the suite from growing slow again?

Track total suite time and the number of context starts per build as metrics, and alert when they rise. Some teams add a check that fails if the number of distinct contexts grows above an agreed limit, so a new unique combination is a conscious decision.

7Conclusion

In this answer, we reduced a 40-minute Spring Boot test suite. We measured per-class times and context starts, standardised configuration so the Spring test context cache is reused instead of defeated by different @MockitoBean and property combinations, shared Testcontainers as singletons, ran tests in forks and timing-balanced shards, and replaced full @SpringBootTest classes with slice tests or plain unit tests where possible.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by measuring. The Surefire and Failsafe reports give time per test class, and usually a small fraction of classes takes most of the time. I would also turn on debug logging for Spring's test context cache to see how many contexts start.

Then, if they want more

In Spring Boot suites the biggest cause is often the context cache being defeated. Spring reuses an application context across test classes only when the configuration is identical, and the key includes profiles, properties and the set of beans replaced with @MockitoBean.

So when each class mocks a slightly different set of beans or sets one extra property, Spring starts a new context each time, several seconds each, and the default cache of 32 starts evicting. The fix is a shared base class or annotation with one agreed set of mocks and properties, and avoiding DirtiesContext.

Second, I would make Testcontainers singletons, started once per JVM, or use ServiceConnection on a shared test configuration, instead of one container per class. Third, run test classes in parallel forks and split the suite across CI agents using timing data.

And finally, replace full SpringBootTest classes with WebMvcTest or DataJpaTest slices, or plain unit tests, wherever the whole application is not needed.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 6
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.
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 "CI test time grew from 10 to 40 minutes as the Spring Boot test suite grew. How do you...": https://scrivio-interview-library.netlify.app/java/version-control-and-ci/3011deacc9/