Scrivio Interview library
LeadershipAdvanced7 min read · updated 12 November 2026

Test code across your organisation mixes @InjectMocks, @MockitoBean in full Spring contexts, and hand-written constructors, and test suites take 40 minutes partly because of many distinct Spring contexts. What testing conventions would you set?

I would set three test types with clear rules. Unit tests build the class directly through its constructor with Mockito mocks or fakes and no Spring context. Slice tests such as @WebMvcTest and @DataJpaTest cover framework integration with a small, stable set of @MockitoBean replacements. Full @SpringBootTest is kept for a few wiring tests. Because every distinct set of @MockitoBean definitions creates a new cached context, we standardise shared test configurations so contexts are reused, measure context count and suite time in CI, publish templates, and review changes that add new contexts.

Why this question is asked

A 40-minute test suite changes how people work: they stop running it locally, push and wait, and batch changes into larger, riskier pull requests. When part of the cause is many Spring contexts, the problem is a lack of conventions rather than slow machines, which makes it a leadership problem. Interviewers ask this to see whether we understand Spring's test context cache well enough to explain why the suite is slow, and whether we can set conventions that fix it and stay fixed. In this answer, we will recap how the context cache works, see how mixed styles create dozens of contexts, define the three test types, standardise configuration, and set up measurement and review.

1A Quick Recap of the Spring Test Context Cache

Starting a Spring application context for a test takes time, often 5 to 20 seconds for a real service, because Spring scans components, creates beans, connects to databases and runs auto-configuration. To avoid paying that for every test class, the Spring TestContext Framework caches contexts. Two test classes share a context when their context configuration is identical: the same configuration classes, active profiles, properties, context customisers and bean overrides.

The key word is identical. A @MockitoBean (or the older @MockBean) changes the context, because it replaces a bean, so it becomes part of the cache key. Test class A that mocks EmailSender and test class B that mocks EmailSender and PaymentGateway get two different contexts, even if everything else is the same. The cache also has a maximum size, 32 by default, after which older contexts are evicted and may be rebuilt later; check your version for the exact setting.

2How Mixed Styles Produce Forty Contexts

Now look at a typical estate. One team writes @SpringBootTest with three @MockitoBean fields, another uses @SpringBootTest with a different two, a third tests plain services with @SpringBootTest because it was in the template, and others use @InjectMocks correctly. Each unique combination is a new context, so a single module can start forty of them. At 12 seconds each, that is eight minutes of context startup, before any test runs, and the waste repeats in every module.

Java
// Each of these classes creates its own context: different bean overrides
@SpringBootTest class OrderFlowTest { @MockitoBean EmailSender email; }
@SpringBootTest class RefundFlowTest { @MockitoBean EmailSender email; @MockitoBean PaymentGateway gw; }
@SpringBootTest class InvoiceTest { @MockitoBean PaymentGateway gw; }
@SpringBootTest class PriceRulesTest { } // a pure logic test that did not need Spring at all
// Log with debug logging for org.springframework.test.context.cache shows the cache statistics,
// for example: size = 4, hitCount = 0, missCount = 4
Why the suite starts so many contexts
Test classBean overridesContext
OrderFlowTestEmailSendercontext 1
RefundFlowTestEmailSender, PaymentGatewaycontext 2
InvoiceTestPaymentGatewaycontext 3
PriceRulesTestnone, but full Boot testcontext 4, not needed
After the conventionshared IntegrationTestConfigone shared context

Notice the last class. Pure logic tests inside @SpringBootTest are the cheapest win, because they need no context at all. The others can share one context if they agree on one set of overrides.

3Convention 1: Unit Tests Without Spring

The first convention is that business logic is tested as plain Java. Classes use constructor injection, so the test builds the class under test directly with new, passing Mockito mocks for external boundaries and fakes or real objects for the rest. No @SpringBootTest, no @MockitoBean, and preferably no @InjectMocks either, because an explicit constructor call is checked by the compiler and cannot silently leave a dependency null.

Java
class PriceRulesTest {
PriceRules rules = new PriceRules(Clock.fixed(T0, ZoneOffset.UTC));
@Test void goldGetsTenPercent() {
assertEquals(new BigDecimal("90.00"), rules.price(new BigDecimal("100"), Tier.GOLD)); // milliseconds, no context
}
}

In most services this covers the majority of tests, and moving them out of Spring is often the single biggest time saving.

4Convention 2: Slices With a Stable Set of Overrides

The second convention covers framework integration: controllers, JSON mapping, security rules, repositories and queries. These use slice annotations, which start only part of the application: @WebMvcTest loads the web layer, @DataJpaTest loads JPA and a database, @JsonTest loads JSON mapping. Slices start faster than a full context, and they make the test's scope obvious.

The overrides are standardised. For each slice type, the platform publishes a shared base class (or, in recent Spring versions, a composed annotation; check your version) that mocks the same small set of service beans for every controller test. Tests extend it instead of declaring their own @MockitoBean fields, so every controller test in the module shares one context. A test that truly needs a different override is allowed, but it is a visible exception.

Java
// Defined once per module: every controller test extends it, so all share one set of overrides
public abstract class WebSliceTest {
@MockitoBean protected OrderService orders;
@MockitoBean protected PaymentService payments;
}
@WebMvcTest
class OrderControllerTest extends WebSliceTest { ... } // same cache key as every other controller test
class RefundControllerTest extends WebSliceTest { ... } // reuses that context

Notice that @WebMvcTest has no controller list here. Naming a controller, as in @WebMvcTest(OrderController.class), also changes the cache key per controller, so loading all controllers in one shared web slice lets a single context serve every controller test. In a large module, a per-controller slice may still be faster to start; the convention should pick one and measure it.

5Convention 3: Few Full Context Tests, One Shared Configuration

Full @SpringBootTest tests are kept for what only they can check: that the application starts, that configuration properties bind, that a few end-to-end flows through real beans work. They all extend or import one shared configuration, with the same profile, the same Testcontainers-backed database and broker, and the same small set of external boundary mocks. The result is one full context per module instead of dozens.

Putting the three conventions together gives a predictable shape: many unit tests in milliseconds, a handful of slice contexts, and one full context.

Step throughTest types and their contexts
  1. Unit testsplain constructors, mocks or fakes, no context
  2. Slice tests@WebMvcTest, @DataJpaTest, shared override config
  3. Full context tests@SpringBootTest, one shared configuration
  4. InfrastructureTestcontainers shared across contexts

4 layers, from the top down. Step through them one at a time.

6Measuring and Reviewing So It Stays Fixed

Conventions erode unless we can see them. In CI we enable debug logging for the context cache, or use a small JUnit extension, to record how many contexts each module starts, and we publish context count and suite time per module on a dashboard. A build check can warn when a pull request increases the context count. Then reviewers look at that warning the way they look at a failing test: a new @MockitoBean combination needs a reason.

We also publish templates for each test type in the service generator, so new code starts right, and we make suite time a team metric with a target, for example under 10 minutes. With these conventions, it is common to see a 40-minute suite fall to 10 to 15 minutes, most of it from removing unneeded contexts rather than from faster tests.

Step throughKeeping the suite fast
  1. Publish templates for each test typeunit, slice, full context
  2. Record context count per module in CIcache statistics
  3. Did this PR add a context?
    YesReviewer asks for the reasonNoMerge as usual
  4. Track suite time as a team metrictarget under 10 minutes

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

7Follow-up questions

Does @DirtiesContext make this worse?

Yes. It throws the context away after a test, so the next test that needs it rebuilds it. It should be rare and justified, and isolating test data is usually the better fix.

Why not just raise the cache size?

It can help when contexts are evicted and rebuilt, but every cached context holds memory, threads and connections. Reducing the number of distinct contexts fixes the cause; a bigger cache only treats a symptom.

Should @InjectMocks be banned?

Not banned, but discouraged. With a single constructor it works, yet an explicit constructor call is clearer and fails at compile time when a dependency is added, so the template uses it.

8Conclusion

In this answer, we saw that the Spring test context cache shares a context only when the configuration is identical, and that each distinct set of @MockitoBean overrides creates a new context, which is how mixed styles produce dozens of contexts and long suites. The conventions are unit tests without Spring using constructors, slice tests with a standard set of overrides, few full context tests on one shared configuration, plus measurement of context count and suite time in CI, templates, and review of changes that add contexts.

What to say in the interviewAbout 70 seconds aloud

Open with

Much of the 40 minutes is probably context startup. Spring's test framework caches application contexts, but only reuses one when the configuration is identical, and each different set of @MockitoBean overrides is part of that key, so mixed styles create dozens of contexts at ten seconds or more each.

Then, if they want more

I would set three conventions. Unit tests construct the class directly with its constructor and Mockito mocks or fakes, with no Spring context; that covers most business logic and runs in milliseconds.

Slice tests, @WebMvcTest and @DataJpaTest, cover framework integration and import a shared test configuration with a small, stable set of overrides, so all controller tests in a module share one context. Full @SpringBootTest is kept for a few startup and flow tests, all on one shared configuration with Testcontainers.

Then I would make it visible: record context count and suite time per module in CI, warn when a pull request adds a context, publish templates for each test type in the service generator, and track suite time as a team metric. In my experience removing unnecessary contexts is the biggest single saving.

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.
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 "Test code across your organisation mixes @InjectMocks, @MockitoBean in full Spring...": https://scrivio-interview-library.netlify.app/java/mocking/7774b2857b/