Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

In Spring Boot tests teams use @MockitoBean heavily, and the suite starts dozens of application contexts. Explain why and what you would change.

Spring's TestContext framework caches application contexts by their configuration, and @MockitoBean (Spring Framework 6.2's replacement for Spring Boot's deprecated @MockBean) is part of that configuration: each distinct set of mocked beans gives a different cache key, so a new context starts. Dozens of different combinations mean dozens of context startups, often several seconds each. I would standardise a few shared base configurations with the same mocks, move logic that does not need Spring to plain unit tests or slice tests, and watch the context cache statistics to keep the number down.

Why this question is asked

A Spring Boot test suite that takes twenty minutes is often not slow because of its tests. It is slow because it starts the application forty times. Interviewers ask this scenario because the cause is invisible unless we know how Spring caches contexts, and because the fix is a mix of test architecture and team convention. In this answer, we will recap the context cache, see exactly why @MockitoBean creates new contexts, measure the problem, and then go through the fixes: shared base configurations, slice and plain unit tests, and guarding the result.

1A Quick Recap of the Context Cache

Starting a Spring Boot application context for a test, with component scanning, auto-configuration, a database connection pool and perhaps Flyway migrations, often takes 5 to 15 seconds. Spring's TestContext framework avoids paying that for every test class by caching contexts. When a test class needs a context, Spring computes a key from its configuration, and if a context with the same key already exists in the cache, it reuses it.

The key, called the merged context configuration, includes the configuration classes, active profiles, property sources, context initializers and context customizers. Two test classes with exactly the same configuration share one context; any difference means a separate context. The cache is per JVM and holds 32 contexts by default, evicting the least recently used and closing it when full (the size is set with spring.test.context.cache.maxSize).

2Why @MockitoBean Creates New Contexts

@MockitoBean replaces a bean in the context with a Mockito mock. It lives in Spring Framework itself since 6.2, in the bean override support of the test context, and it replaces Spring Boot's @MockBean, which is deprecated since Boot 3.4 and removed in Boot 4. Both work the same way in one important respect: replacing beans changes the context, so the set of overridden beans is part of the cache key. That is correct, because a context where PaymentClient is a mock is a different application from one where it is real.

The consequence is that every distinct combination of mocked beans is a distinct context.

Java
@SpringBootTest class OrderApiTest { @MockitoBean PaymentClient payments; }
@SpringBootTest class RefundApiTest { @MockitoBean PaymentClient payments;
@MockitoBean MailSender mail; }
@SpringBootTest class InvoiceApiTest { @MockitoBean MailSender mail; }
@SpringBootTest class CustomerApiTest { @MockitoBean PaymentClient payments;
@MockitoBean FraudCheck fraud; }
// 4 test classes, 4 different sets of mocks -> 4 cache keys -> 4 context startups
// With 60 test classes and dozens of combinations: dozens of startups at ~8 s each
Cache keys from the example
Test classMocked beansContext
OrderApiTestPaymentClientcontext 1 (new)
RefundApiTestPaymentClient, MailSendercontext 2 (new)
InvoiceApiTestMailSendercontext 3 (new)
CustomerApiTestPaymentClient, FraudCheckcontext 4 (new)
After the fix: all fourPaymentClient, MailSender, FraudCheckcontext 1, reused 3 times

Notice that each class looks reasonable on its own. Each developer mocked exactly what their test needed. The cost only appears in the whole suite, which is why nobody noticed it being added.

3Measuring the Problem

Before changing anything, we confirm the diagnosis. Spring logs context cache statistics at DEBUG level for the logger org.springframework.test.context.cache, including the cache size, hit count and miss count. Each miss is a context startup.

Java
# src/test/resources/application-test.properties or logback-test.xml
logging.level.org.springframework.test.context.cache=DEBUG
// Spring test ApplicationContext cache statistics:
// [DefaultContextCache@1a2b size = 32, maxSize = 32, parentContextCount = 0,
// hitCount = 140, missCount = 47]

Here 47 misses mean 47 startups, and a size equal to maxSize means the cache is full and evicting, so some contexts are even being started twice. At 8 seconds each, that is over six minutes of pure startup. The log line's exact format varies by version, but the counts are what matter.

4Fix 1: A Few Shared Base Configurations

The main fix is to make test classes agree on their configuration. We define a small number of base classes or composed annotations, each with a fixed set of mocks, and the integration tests use one of them. A test that does not need a particular mock can simply ignore it; an unused mock costs nothing, while a different set of mocks costs a whole context.

Java
@SpringBootTest
@ActiveProfiles("test")
abstract class ApiTestBase {
@MockitoBean protected PaymentClient payments; // external systems we never call in API tests
@MockitoBean protected MailSender mail;
@MockitoBean protected FraudCheck fraud;
}
class OrderApiTest extends ApiTestBase { ... } // all four classes now share one context
class RefundApiTest extends ApiTestBase { ... }
// missCount: 47 -> 6

Spring resets these mocks after each test method by default, so sharing them does not leak stubbing from one test to the next. The convention is the important part: a team rule, enforced in code review or with an ArchUnit check, that integration tests extend one of the approved bases instead of declaring their own @MockitoBean fields. The base classes usually mock the same thing, the boundaries to external systems, which is where mocks belong in an integration test anyway.

5Fix 2: Do Not Start a Context When It Is Not Needed

Many of the dozens of contexts come from tests that never needed the whole application. A test of discount rules in a service class needs no Spring at all: constructing the service with plain Mockito mocks or fakes runs in milliseconds. A controller test only needs the web layer, which @WebMvcTest starts as a slice, a much smaller context with only MVC components, where @MockitoBean supplies the service the controller calls. Repository tests need @DataJpaTest, not the whole application.

Slice contexts are cached by the same rules, so they should also share mock sets, but each one starts far faster than a full @SpringBootTest. Moving tests down to the cheapest level that still tests what they mean to test usually removes more startup time than any other change.

Step throughChoosing the cheapest test that still works
  1. Does the logic need Spring at all?
    YesContinueNoPlain unit test with mocks or fakes
  2. Only the web layer or only persistence?
    Yes@WebMvcTest or @DataJpaTest sliceNoContinue
  3. Full @SpringBootTestextend a shared base with the standard mocks

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

6Guarding the Result

Without a guard, the number of contexts grows back. Two cheap measures help. First, keep the cache statistics in the CI log and track the miss count per build; a jump from 6 to 15 points at the pull request that added new combinations. Second, avoid @DirtiesContext, which throws a context away and forces a restart; it is sometimes needed, but each use should be justified. Newer Spring versions also reduce the cost of many cached contexts in other ways, for example by pausing contexts that are not in use (check your version), but fewer contexts remains the real fix.

7Follow-up questions

Is @MockitoSpyBean affected in the same way?

Yes. @MockitoSpyBean, which wraps a real bean in a spy, is also a bean override and part of the cache key. Spies should be standardised in the base configurations in the same way as mocks.

Why not raise the cache size instead?

A bigger cache only stops evictions; every distinct context still has to start once. It also keeps more contexts alive in memory, each with its own connection pools and threads, which can exhaust database connections. Raising the size is a last resort after reducing the number of distinct configurations.

8Conclusion

In this answer, we saw that Spring's TestContext framework caches application contexts by their merged configuration, and that @MockitoBean, Spring Framework 6.2's replacement for Boot's deprecated @MockBean, is part of that configuration, so every distinct set of mocked beans starts a new context. We confirmed it with the context cache statistics, then fixed it by standardising a few shared base configurations with the same mocks, moving tests that do not need the whole application to plain unit tests or slices, and guarding the miss count in CI.

What to say in the interviewAbout 90 seconds aloud

Open with

The suite starts dozens of contexts because Spring caches test contexts by their configuration, and mocked beans are part of that configuration. @MockitoBean, which Spring Framework 6.2 introduced to replace Spring Boot's deprecated @MockBean, overrides a bean in the context, so the set of overrides goes into the cache key.

Then, if they want more

If one test class mocks PaymentClient, another mocks PaymentClient and MailSender, and a third mocks only MailSender, that is three different keys and three context startups, each maybe eight seconds. Every class looks fine alone; the cost only shows across the suite.

First I would measure it with DEBUG logging on org.springframework.test.context.cache, which prints the hit and miss counts; each miss is a startup. Then the main fix is a few shared base configurations, for example an ApiTestBase that mocks the standard external boundaries, payments, mail and fraud check, and every API test extends it, so they all share one context.

Mocks are reset after each test, so sharing them is safe. Second, I would move tests down to the cheapest level: logic tests become plain unit tests with Mockito or fakes, controller tests become @WebMvcTest slices, and repository tests use @DataJpaTest.

Finally, I would track the miss count in CI and avoid @DirtiesContext unless justified, so the number does not creep back up.

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 "In Spring Boot tests teams use @MockitoBean heavily, and the suite starts dozens of...": https://scrivio-interview-library.netlify.app/java/mocking/0e6bd72209/