title: Spring boot and Database testing with connection pool
body: <p>I am trying to create tests for my app which connects to a database. The DataSource is a conection pool (Hikari).</p>
  
  <p>Here is my test configuration:</p>
  
  <pre><code>@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);
      }
  }
  </code></pre>
  
  <p>Here is my test class:</p>
  
  <pre><code>@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());
      }
  }
  </code></pre>
  
  <p>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). </p>
  
  <p>I believe the problem is because of the @Sql annotation which causes <code>DataSourceInitializer -s</code> to be created to execute the cleanup script but the connections are never returned to the pool. </p>
  
  <p>When I set MaximumPoolSize to 4 all tests are successfully completed. I cannot tell if I have made a configuration error or if this is a bug in Spring.</p>