Quick revision
The short answer
I would move test overrides into a shared test support library with one configuration per concern, such as a fixed clock, fake external clients and test security, so test classes declare identical setups and share cached contexts. Real wiring with Testcontainers and @ServiceConnection becomes the default, with replacements only at true external boundaries, applied through a common meta-annotation using @TestBean or @MockitoBean. Context counts are reported per build against a budget, and every override must explain in review what production behaviour it replaces and why.
What to remember
In this answer, we saw that many slightly different test configurations break context caching and make tests diverge from production wiring. The fix is a shared test support library with one configuration per concern and meta-annotations for common test kinds, real wiring with Testcontainers and @ServiceConnection, replacements only at external boundaries through @TestBean or @MockitoBean in shared places, context counts reported per build against a budget, and a review rule that every override explains what it replaces and why.
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.
I would move test overrides into a shared test support library with one configuration per concern, such as a fixed clock, fake external clients and test security, so test classes declare identical setups and share cached contexts. Real wiring with Testcontainers and @ServiceConnection becomes the default, with replacements only at true external boundaries, applied through a common meta-annotation using @TestBean or @MockitoBean. Context counts are reported per build against a budget, and every override must explain in review what production behaviour it replaces and why.
Why this question is asked
In a large codebase, test configuration grows one small decision at a time. Someone needs a fixed clock and writes a nested configuration; someone else mocks a repository to make a slow test fast; a third team copies both and changes one line. Each choice is reasonable alone, but together they create dozens of slightly different application contexts, slow builds, and tests that no longer resemble production. Interviewers ask this design question to see whether we can find the root cause and set guidance that teams will follow. In this answer, we will see why the variations are costly, build a shared test support library, prefer real wiring, standardize how beans are replaced, measure contexts, and review overrides.
1Why Many Small Variations Are Expensive
Spring's TestContext framework caches application contexts between test classes. The cache key is the merged configuration of a test class: its configuration classes, imports, profiles, properties, context customizers and bean overrides. If two classes produce the same key, the second reuses the first context. If anything differs, even a nested class with identical content but a different name, a new context starts.
Starting a Spring Boot context with a database container and a few hundred beans can take 5 to 15 seconds. A module with 40 distinct contexts spends several minutes only on startup. The cache also has a size limit, 32 contexts by default, so a build with more variations evicts and restarts contexts, which makes it even slower and can leave containers and thread pools running longer than expected.
The second cost is quieter. Every replaced bean is a place where the test runs different code from production. When tests replace repositories, message publishers or transaction behaviour, they can pass while the real wiring is broken.
2A Shared Test Support Library per Concern
I would create a test support library, published like any other internal library, with one well-named configuration per concern. FixedClockTestConfig provides a controllable clock. FakePaymentClientTestConfig provides an in-memory fake of the payment provider with a few scenario switches. TestSecurityConfig provides JWT personas. Each is a top-level @TestConfiguration, and they are combined through a few meta-annotations that represent common test kinds.
Notice what this does to the cache. Every class annotated with @ServiceIntegrationTest has the same configuration, so the whole module may need one or two contexts instead of thirty. It also makes tests easier to read, because the annotation says what kind of test this is.
3Prefer Real Wiring; Replace Only External Boundaries
The guidance I would write is short: inside the service, use the real beans; replace only things that leave the process and that we cannot run in a test, such as a third-party payment API or an email provider. Databases, message brokers and caches are not external boundaries in this sense, because Testcontainers can run the real thing. With @ServiceConnection on a container field, Spring Boot creates the connection details from the container, so no property tricks or replaced beans are needed.
The reason is that bugs live in the wiring: a transaction boundary in the wrong place, a serializer configured differently, a missing index. A test that mocks the repository cannot find any of them.
- Controllers, services, repositoriesreal beans from the application
- Database, Kafka, Redisreal engines in Testcontainers via
@ServiceConnection - Clockshared fixed clock from the support library
- Payment provider, email, partner APIsshared fakes or WireMock: the only replacements
4 layers, from the top down. Step through them one at a time.
Everything above the last layer is production wiring.
4Standardize How Beans Are Replaced
When a replacement is needed, it should be done one way. Spring Framework 6.2 provides @TestBean for a replacement built by a factory method and @MockitoBean or @MockitoSpyBean for mocks and spies, replacing Boot's deprecated @MockBean. I would put the common ones in the shared meta-annotation or a base class, so the set of overrides is identical across classes. A class that needs one extra mock still creates a new context, so the guidance is to add per-class overrides only when the test cannot be written otherwise, and to promote frequently needed overrides into a second shared test kind.
I would also ban spring.main.allow-bean-definition-overriding=true in test properties, because it hides real duplicate beans, and replace nested @Configuration classes with the shared ones.
5Measure Context Counts and Set a Budget
We cannot manage what we do not see. Spring's test context cache logs its statistics, including size, hit count and miss count, when the logger org.springframework.test.context.cache is set to DEBUG. A small TestExecutionListener in the support library can also record each distinct context key and the classes that created it, and write a summary at the end of the build.
With this, each module gets a budget, say at most five contexts, shown on the build dashboard. A pull request that adds a new context is visible, and the summary says which classes to fix.
6Review Overrides Like Production Code
Finally, every override must explain itself. The rule in code review is that each @TestBean, @MockitoBean or test configuration states in a short comment which production behaviour it replaces and why the real one cannot be used. Without a good reason, the reviewer asks for real wiring. This turns overrides from a habit into a decision, and it creates a natural place to notice when an override is no longer needed, for example after the team adds a Testcontainers setup for a dependency that used to be mocked.
7Follow-up questions
How would you detect tests that pass only because of an override?
Run the suite once with the override removed, in a scheduled build or a dedicated job, using real wiring through Testcontainers or a WireMock stub at the network level instead of the bean replacement. Tests that fail only in that run depend on the override hiding something, either a real bug or a gap in the fake. For fakes, contract tests that run the same scenarios against the fake and the real provider's sandbox keep them honest.
Doesn't sharing one context make tests depend on each other?
It can, if tests leave state behind. Shared contexts need clean data per test, for example unique identifiers or cleanup in @AfterEach, and resettable fakes. Mockito beans declared with @MockitoBean are reset after each test by default, which helps. The time saved by sharing contexts is usually far larger than the effort of keeping tests independent.
What about @DirtiesContext?
@DirtiesContext throws the context away after a test, so the next class must start a new one. It should be rare and justified in review like an override. Most uses can be replaced by resetting the state the test changed.
8Conclusion
In this answer, we saw that many slightly different test configurations break context caching and make tests diverge from production wiring. The fix is a shared test support library with one configuration per concern and meta-annotations for common test kinds, real wiring with Testcontainers and @ServiceConnection, replacements only at external boundaries through @TestBean or @MockitoBean in shared places, context counts reported per build against a budget, and a review rule that every override explains what it replaces and why.
Open with
The root problem is that every variation creates a new cache key, so the test context cache cannot reuse contexts, and each override makes the test less like production.
Then, if they want more
I would fix both with a shared test support library. It has one top-level TestConfiguration per concern, a controllable fixed clock, fakes for real external clients like the payment provider, and test security personas, plus a few meta-annotations such as ServiceIntegrationTest that combine them.
Classes that use the same annotation have the same configuration, so a module goes from thirty contexts to two or three. The guidance is to prefer real wiring: databases, Kafka and Redis run in Testcontainers with ServiceConnection, and we only replace true external boundaries.
When we do replace beans, we use TestBean or MockitoBean, declared in the shared annotation or a base class, not ad hoc per class, and we never enable bean overriding in test properties.
To keep it that way, I would turn on the test context cache debug logging and a small listener that reports contexts per build, with a budget per module on the dashboard. And in review, every override needs a comment saying which production behaviour it replaces and why.
To find tests that only pass because of an override, I would run them periodically with real wiring instead.
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.
- 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 "Across many services, tests define dozens of slightly different @TestConfiguration...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/e80b953758/