草庐IT

java - Spring Boot JDBC-Test DB Connection Leak 运行所有测试时

coder 2023-10-12 原文

我按照以下方式构建了我的测试。

@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 {

}

对于每个测试类,我都扩展了这个类以避免代码重复。所以一个典型的测试类看起来像这样。

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 {

    }


}

我目前有 66 个测试用例在运行,所有这些用例都连接到一个预初始化的 MySQL Db 模式,并运行测试访问这个数据库。所有运行在最后回滚的事务上。我面临的问题是,我所有的测试都在运行并且不释放数据库连接。因此,我编写的测试越多,它所持有的数据库连接数就越高。这会造成某种数据库连接泄漏。 我知道在这样的实例中可以增加数据库连接。但它使测试高度不可扩展。我尝试使用 @DirtiesContext(classMode = ClassMode.AFTER_CLASS) 并没有解决问题。无论如何要在类(class)结束后释放数据库连接。

最佳答案

我认为我们可能做的唯一奇怪的事情是放弃嵌入式数据库支持并连接实际的数据库实例来运行测试,这是至关重要的,因为我们的数据模型太复杂而无法模拟或包含在嵌入式数据库中。

看起来它为每个测试类上下文创建了一个连接池,但在类结束后不会释放它。

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

此外,由于 spring 缓存服务实现跨测试必须使用 @DirtiestContext 终止上下文。现在连接已正确释放。

关于java - Spring Boot JDBC-Test DB Connection Leak 运行所有测试时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47387417/

有关java - Spring Boot JDBC-Test DB Connection Leak 运行所有测试时的更多相关文章

随机推荐