我正在将Dropwizard框架与JDBI和h2-in-memory一起用于我的测试目的.我也写了我的DAO,现在我想用单元测试来测试它们.我来了DBUnit,似乎符合我的要求.
但是如何将它与JDBI集成并用测试数据填充?
解决方法:
我这样实现了:
我创建了一个基础dao类,它设置我的DW环境来为我构建一个DBI实例.这看起来像这样:
@BeforeClass
public static void setup() {
env = new Environment( "test-env", Jackson.newObjectMapper(), null, new MetricRegistry(), null );
dbi = new DBIFactory().build( env, getDataSourceFactory(), "test" );
dbi.registerArgumentFactory(new JodaDateTimeArgumentFactory());
dbi.registerMapper(new JodaDateTimeMapper(Optional.absent()));
}
static DataSourceFactory getDataSourceFactory()
{
DataSourceFactory dataSourceFactory = new DataSourceFactory();
dataSourceFactory.setDriverClass( "org.h2.Driver" );
dataSourceFactory.setUrl( "jdbc:h2:mem:testDb" );
dataSourceFactory.setUser( "sa" );
dataSourceFactory.setPassword( "" );
return dataSourceFactory;
}
public static DBI getDbi() {
return dbi;
}
public static Environment getEnvironment() {
return env;
}
这不会为您指向内存数据库创建数据源.
在实际测试中,您可以在测试之前使用DBI实例创建DAO:
DaoA dao;
DaoB otherDao;
@Before
public void setupTests() throws IOException {
super.setupTests();
dao = dbi.onDemand(DaoA.class);
otherDao = dbi.onDemand(DaoB.class);
}
有了这个你的好处,你可以开始测试.希望有所帮助.
阿图尔
编辑初始化:
我的测试也初始化了.为此,我直接使用dbi来执行sql脚本.例如,测试与test1.sql脚本相关联,该脚本是测试类路径资源.在这种情况下,我需要做的就是读取该脚本并在测试之前运行它.例如这样:
StringWriter writer = new StringWriter();
InputStream resourceStream = this.getClass().getResourceAsStream("/sql/schema.sql");
if(resourceStream == null ) {
throw new FileNotFoundException("schema not found");
}
IOUtils.copy(resourceStream, writer);
Handle handle = null;
try {
handle = dbi.open();
handle.execute(writer.toString());
handle.commit();
} finally {
handle.close();
if(resourceStream != null) {
resourceStream.close();
}
writer.close();
}