NoSuchTableException使用dbunit测试dao类



我将dbunit与内存中的h2数据库一起使用,以测试我编写的DAO类中的方法。套件中的所有测试过去都能成功通过,但后来我重新组织了项目的目录结构,现在我在运行测试套件时收到了NoSuchTableException。我觉得这一定是某种构建路径错误,但我已经两天没有解决了。

以下是包含一些设置方法的测试类的摘录:

@RunWith(PowerMockRunner.class)
@PrepareForTest(DAOUtilities.class)
public class FeedingScheduleDaoImplDBUnitTest extends DataSourceBasedDBTestCase {
private Connection connection;
private FeedingScheduleDaoImpl fsdi = new FeedingScheduleDaoImpl();
@Override
protected DataSource getDataSource() {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setUrl("jdbc:h2:mem:default;DB_CLOSE_DELAY=-1;init=runscript from 'classpath:schema.sql'");
dataSource.setUser("sa");
dataSource.setPassword("sa");
return dataSource;
}
@Override
protected IDataSet getDataSet() throws Exception {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("data.xml");
return new FlatXmlDataSetBuilder().build(inputStream);
}
@Override
protected DatabaseOperation getSetUpOperation() {
return DatabaseOperation.REFRESH;
}
@Override
protected DatabaseOperation getTearDownOperation() {
return DatabaseOperation.DELETE_ALL;
}

@Before
public void setUp() throws Exception {
super.setUp();
connection = getConnection().getConnection();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception {
IDataSet expectedDataSet = getDataSet();
ITable expectedTable = expectedDataSet.getTable("animals");
IDataSet databaseDataSet = getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("animals");
Assertion.assertEquals(expectedTable, actualTable);
}
}

实际上是return new FlatXmlDataSetBuilder().build(inputStream);在生成异常,但我怀疑这是因为getDataSource()方法中没有正确加载模式。

下面是我重组后的新目录结构。测试所需的sql模式文件和xml数据文件都在src/test/resources目录中。

eZoo目录结构

这是我的pom.xml的构建部分。我没有为构建指定任何源目录或资源目录,所以如果我理解正确,应该会将所有资源文件放在默认的target/test-classes目录中。我查过了,他们确实在那里。

<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</plugin>
</plugins>
</build>

任何提示或帮助都将不胜感激。我仍在学习如何使用Maven,我进行这次重组是为了更好地理解标准的Maven项目结构,所以我希望既能修复我损坏的东西,又能更好地学习如何使用Maven。

经过修补,我找到了问题的解决方案。我从xml文件中删除了以下行:

<!DOCTYPE xml>

以下是我找到解决方案的另一个问答链接:https://stackoverflow.com/a/5915063.

最新更新