官方網址:http://www.dbunit.org/
官方介紹:
DbUnit is a JUnit extension (also usable with Ant) targeted for database-driven projects that, among other things, puts your database into a known state between test runs. This is an excellent way to avoid the myriad of problems that can occur when one test case corrupts the database and causes subsequent tests to fail or exacerbate the damage.
DbUnit has the ability to export and import your database data to and from XML datasets. Since version 2.0, DbUnit can works with very large dataset when use in streaming mode. DbUnit can also helps you to verify that your database data match expected set of values.
1. Dbunit無法識別mysql5的bit資料類型,所以需要編寫新的DataTypeFactory,對bit類型作處理。
package net.jim.database.dbunit;
import java.sql.Types;
import org.dbunit.dataset.datatype.DataType;
import org.dbunit.dataset.datatype.DataTypeException;
import org.dbunit.ext.mysql.MySqlDataTypeFactory;
public class MySql5DataTypeFactory extends MySqlDataTypeFactory {
public DataType createDataType(int sqlType, String sqlTypeName)
throws DataTypeException {
if (sqlType == Types.OTHER) {
// BOOLEAN
if ("bit".equals(sqlTypeName)) {
return DataType.BOOLEAN;
}
}
return super.createDataType(sqlType, sqlTypeName);
}
}
2. 擴充dbunit的DatabaseTestCase類,實現getConnection()和getDataSet()方法,這樣,在寫測試案例的時候只需要實現該抽象類別即可。
package net.jim.site.dbunit;
import java.io.FileInputStream;
import net.jim.database.dbunit.MySql5DataTypeFactory;
import net.jim.site.util.TestUtil;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
public abstract class DatabaseTestCase extends org.dbunit.DatabaseTestCase {
@Override
protected IDatabaseConnection getConnection() throws Exception {
IDatabaseConnection connection = new DatabaseConnection(TestUtil
.getConnection());
DatabaseConfig config = connection.getConfig();
config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new MySql5DataTypeFactory());
return connection;
}
@Override
protected IDataSet getDataSet() throws Exception {
return new XmlDataSet(new FileInputStream(
"src/test/net/jim/site/dbunit/SiteData.xml"));
}
}