top of page

Spring integration testing IV: Reusing application context

  • Cyril Sahula
  • May 19, 2023
  • 2 min read

Updated: Dec 14, 2023




This article belongs to a series about integration testing. I recommend reading the kick-offwhere I put links to the whole series.


What is Spring context?

The Spring context is initialized during the booting of an application. The basic version of applications boots in seconds and the more advanced in tens of seconds or a couple of minutes. It depends on a number of dependencies and their complexity. The application context contains everything that is initialized and runs in an application that is deployed on an application server. The time is shown at the end of the boot in the application stack-trace:



What is context reusing

The context reusing benefit is demonstrated in the picture below. The first test case includesthe boot time of an application and the rest of the test cases use the same context as case one. This is how the spring integration test library works by default and it is described in the documentation.



What can we do wrong to destroy the context reusing

We can mock or spy application beans or register new ones in a test phase. If the context adjustment is for all test cases it is OK. I avoid changing the context for individual test cases. It influences the next test cases and it is complicated to remove such adjustments in a good way. In most projects, developers solve it with annotation @DirtiesContext. But it causes thatcontext is started for each test case and the run of all test cases takes an intolerable amount of time. It means that when an application boot lasts for 20 seconds and has 15 test classes, then the time difference is: 5 min vs 35 seconds.


Another problem with such annotations is that when @MockBean and @DirtiesContext areused, the test cannot run in parallel, as is explained in the documentation.


Conclusion

I always find a reasonable way to avoid changing the application context during the testing time. The result is that our application has up to 200 test integration test cases for our application. The whole test run takes around 2 minutes. Without mocking/spying more of theproduction code is tested. The nice side effect is that even though we do not focus on having a big test code coverage, the project has code coverage of around 95% because our main testing layer is integration testing.


Pros

  • significantly faster testing runs

  • less mocking = covering production implementations

  • mocking is much better on edges on the application APIs like Green mail, OkHttp,Testcontainers, etc.

Cons

  • Almost none. It just takes more time to configure it but it is negligible pros because itis an easy way to hell :)

Commentaires


Les commentaires sur ce post ne sont plus acceptés. Contactez le propriétaire pour plus d'informations.
bottom of page