我正在尝试为连接数据库的应用程序创建测试。数据源是一个连接池(光)。
这是我的测试配置:
@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);
}
}
这是我的测试课:
@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。当我运行测试类时,前两个测试已成功完成,而其余测试失败,因为该池耗尽了连接(连接超时)。
我相信问题是由于@Sql批注引起的,该批注会导致DataSourceInitializer -s
创建执行清理脚本,但连接永远不会返回到池中。
当我将MaximumPoolSize设置为4时,所有测试均成功完成。我无法确定我是否犯了配置错误,或者这是否是Spring中的错误。
在getConnection
获取从资产池的连接。更改测试以正确关闭获取的连接,如下所示:
@Test
public void test1() throws SQLException {
try (Connection connection = dataSource.getConnection()) {
log.info("catalog:" + connection.getCatalog());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句