dbunit介绍及使用

官方网址: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"));
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值