Skip to content

Instantly share code, notes, and snippets.

@mrserverless
Last active April 8, 2019 10:17
Show Gist options
  • Save mrserverless/9a50e11dbd8661271220 to your computer and use it in GitHub Desktop.
Save mrserverless/9a50e11dbd8661271220 to your computer and use it in GitHub Desktop.
Dropwizard JDBI Unit Test abstract class using H2 by default.
public abstract class JdbiUnitTest {
protected DBI dbi;
private Handle handle;
private Liquibase liquibase;
protected abstract void setUpDataAccessObjects();
@Before
public void setUpDatabase() throws Exception {
Environment environment = new Environment( "test-env", Jackson.newObjectMapper(), null, new MetricRegistry(), null );
dbi = new DBIFactory().build( environment, getDataSourceFactory(), "test" );
handle = dbi.open();
migrateDatabase();
setUpDataAccessObjects();
}
@After
public void tearDown() throws Exception {
liquibase.dropAll();
handle.close();
}
private void migrateDatabase() throws LiquibaseException {
liquibase = new Liquibase("migrations.xml", new ClassLoaderResourceAccessor(), new JdbcConnection(handle.getConnection()));
liquibase.update("");
}
protected DataSourceFactory getDataSourceFactory()
{
DataSourceFactory dataSourceFactory = new DataSourceFactory();
dataSourceFactory.setDriverClass( "org.h2.Driver" );
dataSourceFactory.setUrl( "jdbc:h2:./build/h2db" );
dataSourceFactory.setUser( "sa" );
dataSourceFactory.setPassword( "sa" );
return dataSourceFactory;
}
}
@tzachz
Copy link

tzachz commented May 20, 2015

Nice, thanks! converted into a JUnit ExternalResource rule, for easier reuse: https://gist.github.com/tzachz/81038a9f70dcb3dca8cd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment