LiquibaseMigration implements Supplier<DatabaseMigrationState> { @Override public DatabaseMigrationState get() { try { Connection c = dataSource.getConnection(); try { JdbcConnection connection = new JdbcConnection(c); Database database = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(connection); Liquibase liquibase = new Liquibase(getMigrationPath(), new ClassLoaderResourceAccessor(), database); List<ChangeSetStatus> changesets = liquibase .getChangeSetStatuses(new Contexts(), new LabelExpression()); LiquibaseMigrationWatcher w = new LiquibaseMigrationWatcher(changesets); liquibase.setChangeExecListener(w); liquibase.update(new Contexts(), new LabelExpression()); return new DatabaseMigrationState(w.isMigrated(), w.getCurrentVersion()); } finally { c.close(); } } catch (SQLException | LiquibaseException e) { logger.error("Cannot migrate database.", e); throw new RuntimeException(e); } } @Inject  LiquibaseMigration(final PooledDataSource dataSource); String getMigrationPath(); void setMigrationPath(final String migrationPath); @Override DatabaseMigrationState get();  }
@Test public void testExitAndCloseOnUnexpectedException() throws Exception { DatabaseResource resource = new DatabaseResource(); try (ITestDatabase db = resource.createDatabase(); Connection c = db.getConnection()) { assertFalse(hasTestTable(c)); PooledDataSource ps = mock(PooledDataSource.class); Connection testConnection = db.getConnection(); Mockito.doReturn(testConnection).when(ps).getConnection(); DatabaseFactory mockFactory = mock(DatabaseFactory.class); doThrow(BadRequestException.class) .when(mockFactory) .findCorrectDatabaseImplementation(any()); DatabaseFactory.setInstance(mockFactory); try { LiquibaseMigration listener = new LiquibaseMigration(ps); listener.get(); Assert.fail(); } catch (BadRequestException e) { assertNotNull(e); } assertTrue(testConnection.isClosed()); assertFalse(hasTestTable(c)); } }