Scrivio Interview library
DebuggingIntermediate5 min read · updated 12 November 2026

After adding @MockitoBean for a repository in one test class, the test suite became much slower and a different test class started failing because a mock leaked. Explain both effects.

The suite slowed down because bean overrides are part of the context cache key, so a new combination of mocks forces a brand new application context instead of reusing a cached one. The other class failed because mocks are reset after each test by default, but stubbing kept in static or shared helpers, or state that other beans in the cached context derived from the mock, survives and leaks into tests that share that context. We fix both by grouping tests with the same mocks in a shared base class and by preferring slices or plain unit tests over many full-context tests with different mocks.

Why this question is asked

One small annotation causing two unrelated-looking symptoms is a classic test-suite puzzle. Both symptoms come from the same mechanism: Spring keeps application contexts alive between test classes and reuses them. Interviewers ask this to see whether we understand that mechanism well enough to explain a slowdown and a cross-test failure from first principles. In this answer, we will recap the context cache, explain the slowdown, reproduce a leak and explain why it happens, and then fix both.

1A Quick Recap of the Context Cache

The Spring TestContext framework caches each application context it starts, inside the JVM, keyed by the test class's merged configuration: configuration classes, profiles, properties and context customizers. Bean overrides such as @MockitoBean are context customizers. A test class whose key matches a cached context gets that same context, with the same singleton beans, already started.

This sharing is what makes integration test suites affordable. It also means that test classes are not isolated from each other: they share beans, and whatever state those beans hold.

2Effect 1: Why the Suite Got Slower

Before the change, suppose 120 test classes extended one base class and shared a single context. The new class adds @MockitoBean for OrderRepository. Its key now differs, so Spring starts a second context for it: new connection pool, new Flyway run, new Kafka consumers, perhaps 10 seconds. If other classes copy the pattern, each with its own slightly different mock set, every variation adds another full startup.

Java
abstract class ApiTestBase { @MockitoBean EmailSender email; } // key K1
class OrderApiTest extends ApiTestBase { } // K1: cache hit
class RefundApiTest extends ApiTestBase {
@MockitoBean OrderRepository repo; // K2: new context, about 10 s
}
// cache statistics: missCount went from 1 to 2, size from 1 to 2

There is a second-order cost too. Every cached context stays in memory with its pool and threads, and once the cache reaches its limit, 32 by default, older contexts are evicted and later rebuilt when needed, so the slowdown can be larger than one startup.

3Effect 2: How a Mock Leaks Into Another Class

Spring resets mocks it created with @MockitoBean after every test method, clearing stubbing and recorded calls. So the mock itself rarely leaks. What leaks is everything around it that the reset does not touch. Here is a common case: a caching service in the same context stores what the mocked repository returned.

Java
class RefundApiTest extends ApiTestBase {
@MockitoBean OrderRepository repo;
@Test void refundsCancelledOrder() {
given(repo.findById(7L)).willReturn(Optional.of(cancelledOrder(7L)));
api.refund(7L); // OrderCache (a real singleton in this context) now holds order 7 as CANCELLED
}
}
class RefundEdgeCaseTest extends ApiTestBase {
@MockitoBean OrderRepository repo; // same key: same context, same OrderCache
@Test void rejectsRefundForPaidOrder() {
given(repo.findById(7L)).willReturn(Optional.of(paidOrder(7L)));
api.refund(7L); // reads CANCELLED from the cache, never asks the mock -> test fails
}
}
Step throughA cached context carrying state between classes
Class ACached contextClass B
stub repo: order 7 CANCELLED
refund(7): cache stores CANCELLED
after test: mock reset, cache untouched
stub repo: order 7 PAID
refund(7)
answer from cache: CANCELLED

6 messages in order. Play them, or step through them one at a time.

The reset clears the mock, but not the state other beans built from it.

Notice that the second class passes when run on its own and fails only after the first, which is the signature of shared state. Other common sources are a mock created by hand with Mockito.mock() in a @TestConfiguration, which Spring does not reset by default, stubbing done once in a static helper or a @BeforeAll, and background work such as a scheduled job or a listener that calls the mock between tests.

4Fix 1: Group Tests That Use the Same Mocks

For speed, we decide on a small number of standard mock sets and put each in a base class, so every class that needs OrderRepository mocked uses the same set and the same context. Mocking a bean that one test does not use costs nothing; a different mock set costs a full startup.

Step throughFixing the slowdown and the leak
  1. Check cache statisticscount contexts and misses
  2. Merge mock sets into base classessame overrides, same context
  3. Find shared statecaches, hand-made mocks, static stubbing
  4. Reset that state per test@BeforeEach or @AfterEach
  5. Move logic tests downslices or plain unit tests

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

5Fix 2: Reset State and Push Tests Down

For the leak, we reset whatever the mock's answers were stored in: clear OrderCache in an @AfterEach, use @MockitoBean instead of hand-made mocks so Spring resets them, and move stubbing out of static helpers into each test. Reaching for @DirtiesContext would also hide the problem, but it throws away the context and makes the speed problem worse.

Finally, a test about refund rules does not need the whole application. A plain unit test of RefundService with Mockito mocks, or a slice, has no shared context to leak through and runs in milliseconds. Keeping full-context tests few, with standard mock sets, solves both effects at their root.

6Follow-up questions

How do I prove a test depends on order?

Run the failing class on its own; if it passes, run it right after the suspect class. JUnit's method and class orderers, or a random order with a fixed seed, help reproduce it reliably on CI.

Why not set reset = MockReset.BEFORE on the mock?

It changes when the mock is reset, but the leak here is not in the mock. The cache and other beans keep their state either way, so the fix has to target that state.

Would @DirtiesContext fix the failing class?

It would hide it by starting a fresh context, at the cost of another full startup each time. It is better to find and reset the shared state, which keeps the suite fast and makes the dependency visible.

7Conclusion

In this answer, we saw that bean overrides are part of the context cache key, so a new combination of mocks starts a new context and slows the suite, and that cached contexts are shared, so although @MockitoBean mocks are reset after each test, stubbing in static helpers, hand-made mocks and state other beans derived from a mock can leak into other classes. We fixed both by grouping tests with the same mocks in base classes, resetting shared state per test, and moving logic tests to slices or unit tests.

What to say in the interviewAbout 80 seconds aloud

Open with

Both effects come from Spring's test context cache. Contexts are cached in the JVM and keyed by the test's merged configuration, and bean overrides like @MockitoBean are part of that key.

Then, if they want more

So when one class added a mock for the repository, its key no longer matched the shared context and Spring had to start a whole new one, with its own pool and consumers. Each new combination of mocks adds another startup, and with the cache limit of 32, evictions can make it worse.

The leak is because classes with the same key share one context and its singleton beans. Spring resets @MockitoBean mocks after each test, so the mock's stubbing is cleared, but anything built from it is not.

For example, a caching bean can keep a value the mock returned in one class and serve it to another class, which then passes alone and fails after the first. Hand-made mocks in a test configuration, stubbing in static helpers and background jobs calling the mock leak the same way.

My fixes are to standardise mock sets in a few base classes so contexts are reused, reset that shared state in @AfterEach rather than using @DirtiesContext, and move logic tests to unit tests or slices that have no shared context.

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 "After adding @MockitoBean for a repository in one test class, the test suite became much...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/3a3b8c172c/