我刚刚意识到DBUnit的本身并不创建表(见如何测试用DbUnit使用普通JDBC和HSQLDB没有面临NoSuchTableException? )。
有没有办法对DBUnit的自动创建一个数据集或DTD表?
编辑:对于一个内存数据库等HSQLDB的简单的测试,一个粗糙的方法可以被用于自动地创建表:
private void createHsqldbTables(IDataSet dataSet, Connection connection) throws DataSetException, SQLException {
String[] tableNames = dataSet.getTableNames();
String sql = "";
for (String tableName : tableNames) {
ITable table = dataSet.getTable(tableName);
ITableMetaData metadata = table.getTableMetaData();
Column[] columns = metadata.getColumns();
sql += "create table " + tableName + "( ";
boolean first = true;
for (Column column : columns) {
if (!first) {
sql += ", ";
}
String columnName = column.getColumnName();
String type = resolveType((String) table.getValue(0, columnName));
sql += columnName + " " + type;
if (first) {
sql += " primary key";
first = false;
}
}
sql += "); ";
}
PreparedStatement pp = connection.prepareStatement(sql);
pp.executeUpdate();
}
private String resolveType(String str) {
try {
if (new Double(str).toString().equals(str)) {
return "double";
}
if (new Integer(str).toString().equals(str)) {
return "int";
}
} catch (Exception e) {}
return "varchar";
}