I'm trying to cover a huge Spring Boot application with integration tests. There are lots of Spring beans within the app. It takes a while to load the Spring context.
So I'm wondering -
- Is Spring clever enough to share the same context between multiple integration tests located in different classes? I mean to avoid initializing the heavy-weight context for each test class.
- What happens when tests 1,2,4 use
TestContextOne
and tests 3,5 useTestContextTwo
? Does Spring launch them in 1,2,4,3,5 order? Or does Spring keep two contexts in memory?
P.S. In other words, is the common practice to use a single "full" Spring Context for all integration tests, instead of writing separate ones for each test?
Another trick that you can use in your integration tests is to force all the beans in the context to be "lazy". This is really useful when running just one integration test, as you do not have to wait for the entire application context to be loaded and initialized. This can significantly improve the time it takes to run a single test.
You may run into situations where beans are being implicitly created (Example: Spring IntegrationFlow). The flow is never directly injected into anything but your classes may have references to beans that the flow creates. In this case you either need to @Autowire your flow (to insure the implicit beans get created) or you can get creative with a BeanPostProcessor.
I created the following post processor and you just have to add it to your testing spring context.
And to use it:
Or you extend it with exclusions (In this example, any bean that is assignable to a Spring Integration flow will NOT be marked as lazy:
One of the main features provided by spring framework for testing an application is the context caching mechanism to avoid exactly what you mention about the load overhead. The spring documentation says that:
With this affirmation in mind you have to understand how the cache mechanism works to determine the best strategy on build your tests. The question here is:
When spring caches the context, it stores this context in memory using what key?
. According to documentation, the key is based on some parameters of the container:Based on this information I may suggest you that the best practice is organize your tests in a way that they use the same set of context parameters (that is, the same cache key) to benefit from cache mechanism and avoid another context to be loaded. Spring documentation also gives an example: