[英]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);
}
}
這是我的測試類:
@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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.