Spring Boot JDBC-Test DB Connection Leak When running all the tests

Viewed 1970

I have structured my test in the following way.

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {BizServiceTestContextConfig.class})
@JdbcTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource( {
    "file:${apps.config.root}/test_config/bizservice.test.properties",
    "file:${apps.config.root}/test_config/dcs.test.properties"
})
@PropertySource(name = PropSourceKey.SCHEDULER_PROPERTIES, value = "file:${apps.config.root}/config/scheduler.properties")
@PropertySource(name = PropSourceKey.MESSAGING_PROPERTIES, value = "file:${apps.config.root}/config/messaging.properties")
public abstract class BizServiceTest {

}

For each test class I have extended this class to avoid code duplication.So a typical test class would look like this.

public class SystemParameterServiceImplTest extends BizServiceTest {

    @Autowired
    private SystemParameterService systemParameterService;

    @Test
    public void testA() throws Exception {

    }

    @Test
    public void testB() throws Exception {

    }

    @Test
    public void testC() throws Exception {

    }


}

I have currently 66 test cases running, all which connect to a pre-initialized the MySQL Db Schema, and run the tests accessing this database. All run on transactions which are rollbacked at the end. The problem I am facing is that, all my tests run and do not release the DB connections. So the more tests I write the higher number of db connections it holds on to. This creates kind of a DB connection leak. enter image description here I know the db connections can be increased in an instance like this. But it makes testing highly unscalable. I tried using @DirtiesContext(classMode = ClassMode.AFTER_CLASS) which did not solve the problem. Is there anyway to release the db connections after the class.

1 Answers

The only weird thing I think we may have done is foregoing embedded DB support and wiring the actual DB instance to run the tests, which is vital since our Data model is too complex to be mocked or included in Embedded dbs.

ooks like for each test class context it creates a connection pool but doesn't release it once the class is over.

So I used a concrete Data Source[Hikari] implementation and explicitly got rid of the pool @ AfterClass.

Also since spring caches service implementations across test had to kill off the context afterclass with @DirtiestContext. Connections are released properly now.

Related