使用 Antrun Maven 插件解决了这个问题,其中 DELETE 操作设置为在集成后测试阶段运行,INSERT 操作设置为在预集成测试阶段运行并使用 ant-contrib 库。我已将 INSERT 操作放在 trycatch 块上。如果捕获到异常,则使用 DELETE 操作,然后构建失败。
这是 insertOperation.xml ant 脚本的代码示例(我不会放置“project”和“target”标签,但“target”名称是“dbunit-insert”):
// Classpath used is Maven's Test scope classpath
<taskdef resource="net/sf/antcontrib/antcontrib.properties"
classpathref="maven.test.classpath"/>
// Classpath used is Maven's Test scope classpath
<taskdef name="dbunit" classname="org.dbunit.ant.DbUnitTask"
classpathref="maven.test.classpath"/>
<trycatch>
<try>
<dbunit driver="your.driver" url="your.database.url"
userid="your.database.username" password="your.database.password"
schema="your.database.schema">
<operation type="INSERT" src="src/main/resources/insertYourDataSet.flat"
format="flat"/>
// I know it has flat format as default but I define it so it won't
// appear NULL on the console during the execution. And although
// you can define the "transaction" parameter on "operation", it will
// only rollback the "operation" in which it is defined. This means
// that if a second file is set for INSERT and you get a problem with it,
// even setting the "transaction" parameter to "true" it won't rollback
// the first INSERT made.
</dbunit>
</try>
<catch>
// XML with DELETE operations
// This XML was created based on the inserted data
// e.g.: if you insert a String with "abc", this will delete it
// This works as a rollback for ALL INSERT operations
// So, if you get a trouble on a second file
// it grants that the first inserted dataset will be deleted.
<ant antfile="src/main/resources/ant/deleteOperation.xml"
inheritrefs="true"/>
// This command will fail Maven build
// print the message you've set and prevent it from running tests
// that rely on the data you tried to insert
<fail message="Failed build due to problem on an INSERT operation"/>
</catch>
</trycatch>
下面是 deleteOperation.xml ant 脚本的代码示例(我不会放置“project”和“target”标签,但“target”名称是“dbunit-delete”):
// Notice that I don't need the ant-contrib library
// That's because DELETE operations are simply ignored if the data
// doesn't exist.
// You won't need a trycatch block, so no ant-contrib here
<taskdef name="dbunit" classname="org.dbunit.ant.DbUnitTask"/>
<dbunit driver="your.driver" url="your.database.url"
userid="your.database.username" password="your.database.password"
schema="your.database.schema">
<operation type="DELETE" src="src/main/resources/deleteYourDataSet.flat"
format="flat"/>
</dbunit>
希望我能帮助某人。