Video in progress
What does @MockitoBean (formerly @MockBean) do in Spring tests, and what does heavy use of it cost?
It replaces a bean in the Spring context with a Mockito mock. Each different set of mocks changes the context configuration, so Spring can't reuse the cached context and starts a new one, which slows the test suite down sharply.
📖 Answer
Since Spring Boot 3.4, @MockBean and @SpyBean are deprecated, replaced by @MockitoBean and @MockitoSpyBean from Spring Framework 6.2. The meaning is the same.
The problem is the context cache. Spring caches the test context by a key, and the key includes the list of mocked beans:
@SpringBootTest class OrderIT { @MockitoBean PaymentClient payment; }
@SpringBootTest class InvoiceIT { @MockitoBean SmsClient sms; }
@SpringBootTest class ReportIT { /* no mock */ }
These three classes are three separate contexts. Each takes 10-15 seconds to start. With 50 classes like this the suite goes past 10 minutes, and "Started Application" shows up in the logs over and over.
What I do:
- gather the mocks for external systems in one abstract base class that all integration tests extend, so there's one context;
- in many cases, testing the real HTTP layer with WireMock is better than
@MockitoBean; - in unit tests there's no Spring at all, and a plain
@Mockis enough.
To see how well the cache is working, turn on logging.level.org.springframework.test.context.cache=DEBUG and it prints the cache statistics.
Sign up to mark studied questions and save your progress.