Connections are not closed and piling up when running @SpringBootTest classes

Solution 1:

It turns out that context was recreated almost with every test class because I was extensively using @MockBean annotation in my tests. Since it affects Spring context, each @MockBean/No MockBean combination in different test classes counts as a different context, i.e.:

  • Test class 1: bean MyService is a MockBean, MyOtherService is not
  • Test class 2: bean MyService is a MockBean, MyOtherService is also a MockBean
  • Test class 3: none of these two beans is a MockBean

In such case, a new Spring context will created for each class because the bean configuration is different, resulting in an increasing number of connections to the datasource.

To (partially) solve this, I looked for patterns in the beans combinations of my test classes and created a new class I called TestMockBeans.

Its sole purpose is to declare as many MockBeans and/or SpyBeans as possible to re-use in similar test configurations. I extend corresponding test classes with TestMockBeans, and then, because they share this similar setup, Spring identifies their contexts as similar and does not recreate a new one for every test class.

As you can guess, not all of my tests throughout the Spring boot app share the same need for Mockbeans (or absence of Mockbeans) so it's only a partial solution, but I hope it will help someone experiencing the same issue to mitigate it.