dbunit: DbUnit is a JUnit extension (also usable with Ant) targeted for database-driven projects

official site, 好久没更新了, 最新版本2.1还是2004年5月的

1. use ant task

<taskdef classpathref="project.classpath" classname="org.dbunit.ant.DbUnitTask" name="dbunit" />

 导出数据

<target name="export">
<dbunit password="${database.password}" userid="${database.userid}" 
   url
="${database.url}" driver="${database.driver}" supportbatchstatement="true">
<export format="xml" dest="data/export-data.xml">
      
<query name="FOO" sql="SELECT COL1, COL2 FROM FOO WHERE COL1=4"/>
      
<table name="BAR"/> 
</export>
</dbunit>
</target>

tip: 不指定query、table, 导出所有的table

导入数据

<target name="clean_insert">
<dbunit password="${database.password}" userid="${database.userid}" 
   url
="${database.url}" driver="${database.driver}">
   
<operation format="xml" src="data/init-data.xml" type="CLEAN_INSERT" />
</dbunit>
</target>

tip:
type: UPDATE, INSERT, DELETE, DELETE_ALL, REFRESH,
      MSSQL_INSERT, MSSQL_REFRESH, MSSQL_CLEAN_INSERT.

比较数据

<target name="compare">
<dbunit password="${database.password}" userid="${database.userid}" 
   url
="${database.url}" driver="${database.driver}">
   
<compare format="xml" src="data/init-data.xml" />
</dbunit>
</target>

2. use code

导出数据

IDatabaseConnection conn = new DatabaseConnection(jdbcConnection, schema); // oracle指定schema
IDataSet dataSet = conn.createDataSet();
XmlDataSet.write(dataSet, 
new FileOutputStream("export-data.xml")); // xml file
FlatXmlDataSet.write(dataSet,new FileOutputStream("export-data.xml")); // flat xml file
XlsDataSet.write(dataSet,new FileOutputStream("export-data.xls")); // xls file
FlatDtdDataSet.write(dataSet,new FileOutputStream("export-data.dtd")); // dtd file
CsvDataSetWriter.write(dataSet, new File("export-data-csv")); // csv file

使用DatabaseSequenceFilter, 解决违反外键约束的问题

IDatabaseConnection conn = new DatabaseConnection(jdbcConnection);
ITableFilter filter 
= new DatabaseSequenceFilter(conn);
// ITableFilter filter = new DatabaseSequenceFilter(conn, tableNames);
IDataSet dataset = new FilteredDataSet(filter, conn.createDataSet());
XmlDataSet.write(dataset, 
new FileOutputStream("export-data.xml"));

导入数据

DatabaseOperation.REFRESH.execute(conn, dataSet);
DatabaseOperation.INSERT.execute(conn, dataSet);

删除数据

DatabaseOperation.DELETE.execute(conn, dataSet);

比较数据

IDatabaseConnection conn = new DatabaseConnection(jdbcConnection);
Compare compare 
= new Compare();
compare.setFormat(
"xml");
compare.setSrc(
new File("export-data.xml"));
compare.execute(conn);

tip: 使用assert进行比较, 作用不大
code: Assertion.assertEquals(expectedTable, actualTable);

3. QueryDataSet: use sql

QueryDataSet queryDataSet = new QueryDataSet(conn);
queryDataSet.addTable(
"orders", ordersQuerySQL);

posted on 2005-08-20 03:17 water ye 阅读(956) 评论(0)  编辑  收藏 所属分类: OtherJava Basic