Video in progress
When @SpringBootTest tests multiply, why does the test suite suddenly become very slow?
Spring TestContext caches the context, and tests with the same configuration reuse it. If each test class brings a different mock, profile or property, the key changes and a new context is started, each taking several seconds.
📖 Answer
The context cache key is the test class's whole configuration: the @SpringBootTest attributes, active profiles, @TestPropertySource, the list of @MockitoBeans, @Import and so on.
The cache usually breaks like this:
@SpringBootTest
class OrderServiceTest {
@MockitoBean PaymentClient payment; // mock set A
}
@SpringBootTest
class RefundServiceTest {
@MockitoBean MailSender mail; // mock set B -> new context
}
@SpringBootTest(properties = "app.feature-x=true") // another new context
class FeatureXTest { }
@DirtiesContext // forces the context to be thrown away
class SomeTest { }
20 classes with an 8-second context each is 2-3 minutes just for startup.
How you tell: logging.level.org.springframework.test.context.cache=DEBUG shows in the log whether a context was taken from the cache or a new one was created. A simpler sign: the Spring banner keeps showing up in the test log.
What you do:
- gather the shared mocks into one abstract base test class;
- keep
@DirtiesContextonly where it's truly needed; - if you don't need the whole context, take narrow slices like
@WebMvcTestand@DataJpaTest.
The cache size is also limited (32 contexts by default): beyond that, old ones are closed and have to be started again.
Sign up to mark studied questions and save your progress.