我将Dropwizard框架与JDBI和h2-in-memory一起用于我的测试目的。我也写了我的DAO,现在我想用单元测试来测试它们。我来了DBUnit,似乎符合我的要求。
但是如何将它与JDBI集成并用测试数据填充?
答案 0 :(得分:8)
我实现了这样:
我创建了一个基础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);
}
这样你就可以开始测试了。希望有所帮助。
阿图尔
编辑init:
我的测试也会初始化。为此,我直接使用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();
}