[英]Spring boot and Database testing with connection pool
I am trying to create tests for my app which connects to a database. 我正在尝试为连接到数据库的应用程序创建测试。 The DataSource is a conection pool (Hikari). DataSource是一个连接池(Hikari)。
Here is my test configuration: 这是我的测试配置:
@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);
}
}
Here is my test 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());
}
}
Notice that the MaximumPoolSize is set to 2. When I run the test class the first two tests are successfully completed and the remaining tests fail because the pool gets depleted of connections (connection timeout). 请注意,MaximumPoolSize设置为2.当我运行测试类时,前两个测试成功完成,其余测试失败,因为池连接耗尽(连接超时)。
I believe the problem is because of the @Sql annotation which causes DataSourceInitializer -s
to be created to execute the cleanup script but the connections are never returned to the pool. 我认为问题是因为@Sql注释导致创建DataSourceInitializer -s
来执行清理脚本,但连接永远不会返回到池中。
When I set MaximumPoolSize to 4 all tests are successfully completed. 当我将MaximumPoolSize设置为4时,所有测试都成功完成。 I cannot tell if I have made a configuration error or if this is a bug in Spring. 我无法判断我是否发生了配置错误,或者这是否是Spring中的错误。
The getConnection
acquires connection from underlying pool. getConnection
从底层池获取连接。 Change your tests to properly close the acquired connection like so: 更改测试以正确关闭所获取的连接,如下所示:
@Test
public void test1() throws SQLException {
try (Connection connection = dataSource.getConnection()) {
log.info("catalog:" + connection.getCatalog());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.