如何使用 DBUnit 与普通的 JDBC 和 HSQLDB 进行测试,而不会遇到 NoSuchTableException?
我正在尝试将DBUnit与普通的JDBC和HSQLDB一起使用,但无法完全使其工作 - 即使我之前已经将DBUnit与Hibernate一起使用并取得了巨大的成功。代码如下:
import java.sql.PreparedStatement;
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
import org.junit.Test;
public class DummyTest {
@Test
public void testDBUnit() throws Exception {
IDatabaseTester databaseTester = new JdbcDatabaseTester("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem", "sa", "");
IDataSet dataSet = new XmlDataSet(getClass().getResourceAsStream("dataset.xml"));
databaseTester.setDataSet(dataSet);
databaseTester.onSetup();
PreparedStatement pst = databaseTester.getConnection().getConnection().prepareStatement("select * from mytable");
}
}
这是有问题的数据集.xml:
<dataset>
<table name="mytable">
<column>itemnumber</column>
<column>something</column>
<column>other</column>
<row>
<value>1234abcd</value>
<value>something1</value>
<value>else1</value>
</row>
</table>
</dataset>
这个测试给了我一个NoSuchTableException:
org.dbunit.dataset.NoSuchTableException: mytable
at org.dbunit.database.DatabaseDataSet.getTableMetaData(DatabaseDataSet.java:282)
at org.dbunit.operation.DeleteAllOperation.execute(DeleteAllOperation.java:109)
at org.dbunit.operation.CompositeOperation.execute(CompositeOperation.java:79)
at org.dbunit.AbstractDatabaseTester.executeOperation(AbstractDatabaseTester.java:190)
at org.dbunit.AbstractDatabaseTester.onSetup(AbstractDatabaseTester.java:103)
at DummyTest.testDBUnit(DummyTest.java:18)
如果我删除 databaseTester.onSetup() 行,我会得到一个 SQLException:
java.sql.SQLException: Table not found in statement [select * from mytable]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(Unknown Source)
at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
at DummyTest.testDBUnit(DummyTest.java:19)
数据集本身正在工作,因为我可以像它应该的那样访问它:
ITable table = dataSet.getTable("mytable");
String firstCol = table.getTableMetaData().getColumns()[0];
String tName = table.getTableMetaData().getTableName();
我在这里错过了什么?
编辑:正如@mlk指出的那样,DBUnit不创建表。如果我在添加数据集之前插入以下内容,一切都会顺利进行:
PreparedStatement pp = databaseTester.getConnection().getConnection().prepareStatement(
"create table mytable ( itemnumber varchar(255) NOT NULL primary key, "
+ " something varchar(255), other varchar(255) )");
pp.executeUpdate();
我发布了一个后续问题,因为 DBUnit 有没有办法从数据集或 dtd 自动创建表?