Spring 使用连接池进行启动和数据库测试

Spring boot and Database testing with connection pool

我正在尝试为连接到数据库的应用程序创建测试。 DataSource 是一个连接池 (Hikari)。

这是我的测试配置:

@Configuration
public class SqlTestConfig {

    @Bean
    DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setMaximumPoolSize(2);
        config.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        config.setJdbcUrl("jdbc:sqlserver://serversql:1433;database=myDatabase");
        config.setUsername("user");
        config.setPassword("password");
        return new HikariDataSource(config);
    }
}

这是我的测试class:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SqlTestConfig.class)
@Slf4j
@Sql(
        scripts = "/clearTables.sql",
        config = @SqlConfig(separator = "GO")
)
public class SqlTest {

    @Autowired
    DataSource dataSource;

    @Test
    public void test1() throws SQLException {
        log.info("catalog:" + dataSource.getConnection().getCatalog());
    }

    @Test
    public void test2() throws SQLException {
        log.info("catalog:" + dataSource.getConnection().getCatalog());
    }

    @Test
    public void test3() throws SQLException {
        log.info("catalog:" + dataSource.getConnection().getCatalog());
    }

    @Test
    public void test4() throws SQLException {
        log.info("catalog:" + dataSource.getConnection().getCatalog());
    }
}

注意 MaximumPoolSize 设置为 2。当我 运行 测试 class 前两个测试成功完成,其余测试失败,因为池耗尽了连接(连接超时).

我认为问题是因为 @Sql 注释导致创建 DataSourceInitializer -s 来执行清理脚本,但连接永远不会返回到池中。

当我将 MaximumPoolSize 设置为 4 时,所有测试都已成功完成。我不知道我是否犯了配置错误,或者这是 Spring.

中的错误

getConnection 从底层池获取连接。更改您的测试以正确关闭获取的连接,如下所示:

@Test
public void test1() throws SQLException {
    try (Connection connection = dataSource.getConnection()) {
        log.info("catalog:" + connection.getCatalog());
    }
}