I have multiple integration tests with @SpringBootTest
.
In some cases, Spring Boot starts multiple application contexts by executing these integration tests (e.g. due to usage of @MockBean
and @SpyBean
on specific test class instead of defining them on common abstract class), and it leads to increased build time or even worse – might crash surefire plugin execution (like in my case).
After identifying and fixing all those cases, now I have only two started application contexts (the first one is without any mocked beans and the second is with mock and spy beans).
I would like to have assertion that indeed after running all tests, the total number of started application contexts haven’t reached some threshold (e.g. number is not exceeding two app contexts). How to achieve that? I found that there is DefaultContextCache
that handles created application contexts, but unclear how to reach that. We could turn on logging by this class (logging.level.org.springframework.test.context.cache: debug
) and it will log the following messages:
Spring test ApplicationContext cache statistics: [DefaultContextCache@44351c52 size = 8, maxSize = 32, parentContextCount = 0, hitCount = 2156, missCount = 8]
by this example size = 8
– displays number of application contexts that are cached (and in this case it’s the total number of app contexts, and there were no evictions by reaching max size). This is useful log for described scenario, but I want to have test that make expected assertion, to prevent adding new application contexts by mistake in the future.