Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

java - Is there any way for DBUnit to automatically create tables?

I just realized that DBUnit doesn't create tables by itself (see How do I test with DBUnit with plain JDBC and HSQLDB without facing a NoSuchTableException?).

Is there any way for DBUnit to automatically create tables from a dataset or dtd?

EDIT: For simple testing of an in-memory database like HSQLDB, a crude approach can be used to automatically create tables:

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";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not really. As the answer you linked points out, the dbunit xml files contain data, but not column types.

And you really don't want to do this; you risk polluting your database with test artifacts, opening up the possibility that production code will accidentally rely on tables created by the test process.

Needing to do this strongly suggests you don't have your db creation and maintenance process adequately defined and scripted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...