我目前正在使用 dbunit(使用 hsqldb)进行编码测试。但是,我在初始化数据库时遇到了一个巨大的问题:
这是代码:
/**
* Init before a test starts
*/
@Before
public void initialise() {
IDataSet dataSetRating = null;
IDataSet dataSetMovie = null;
log.info("enter init test");
try {
con = datasource.getConnection();
icon = new DatabaseConnection(con);
File rating = new File("./src/test/resources/startDatabaseRating.xml");
dataSetRating = new FlatXmlDataSetBuilder().build(rating);
DatabaseOperation.CLEAN_INSERT.execute(icon, dataSetRating);
} catch (Exception e) {
e.printStackTrace();
log.error(e);
System.exit(-1);
}
}
我的创建语句如下所示:
CREATE TABLE Rating
(
rid INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
mid INTEGER FOREIGN KEY REFERENCES Movie(movieId),
rating INTEGER NOT NULL,
);
我的 startDatabaseRating.xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<Rating rid="0" mid="0" rating="1" />
<Rating rid="1" mid="0" rating="2" />
<Rating rid="2" mid="0" rating="3" />
<Rating rid="3" mid="0" rating="4" />
<Movie movieid="0" title="Movie1" moviePath="C" />
<Movie movieid="1" title="Movie2" moviePath="D" />
</dataset>
当我运行测试时,我得到:
java.sql.SQLIntegrityConstraintViolationException:完整性约束违规:外键无动作;SYS_FK_10556 表:评级
为什么会出现此异常,因为 *.xml 文件中仍有数据集。如何解决这个问题?
更新:
CREATE TABLE Movie
(
movieId INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
title VARCHAR(255) NOT NULL,
moviePath VARCHAR(500) NOT NULL
);