DbUnit 的 DBTestCase 的用法(针对扁平XML)

1.dbunit从名字上可以看出,是对有关数据库操作的测试。官网:www.dbunit.org从官网下载dbunit相关的jar包,dbunit还依赖于http://www.slf4j.org所以也需要下载slf4j,使用它的slf4j-api-1.7.7.jar和slf4j-simple-1.7.7.jar。 


dbunit的原理是:它会把数据库表里的数据和一个xml文件里表示的数据关联起来。也就是说 数据库表里的数据可以导出到一个对应的xml里,同时也可以将一个xml里的数据导入到数据库表里。是相互转换的。 
                 数据库表里的数据<===>xml文件 

可以做个测试如下: 

package com.test.dbunit;

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;

public class TestApp {
	
	public static void main(String[] args) throws Exception{
		Class.forName("com.mysql.jdbc.Driver");

		Connection conn = DriverManager.getConnection(
				"jdbc:mysql://localhost/dbunit", "root", "");
		
		IDatabaseConnection connection = new DatabaseConnection(conn);
		QueryDataSet dataSet = new QueryDataSet(connection);
		//将整个person表里的数据导出到 xml文件里
		dataSet.addTable("person");
		//将users表里符合条件的数据导出到xml文件里
		dataSet.addTable("users","select * from users where id < 4");
		//导出到dbunit.xml文件里
		FlatXmlDataSet.write(dataSet,new FileOutputStream("dbunit.xml"));
	}

}

 如果想把某个数据库里的所有表里的数据全部导出到某个xml里,又不想通过addTable一个个来添加的话。则必须通过IDatabaseConnection的createDataSet()来创建IDataSet 

public static void main(String[] args) throws Exception{
		Class.forName("com.mysql.jdbc.Driver");

		Connection conn = DriverManager.getConnection(
				"jdbc:mysql://localhost/dbunit", "root", "");
		
		IDatabaseConnection connection = new DatabaseConnection(conn);
		//如果想把某个数据库里的所有表里的数据全部导出到某个xml里,又不想通过addTable一个个来添加的话。则必须通过IDatabaseConnection的createDataSet()来创建IDataSet
		IDataSet dataSet = connection.createDataSet();
		//导出到dbunit.xml文件里
		FlatXmlDataSet.write(dataSet,new FileOutputStream("dbunit1.xml"));
		//也可以用FlatDtdDataSet导出一个对应的dtd文件
		FlatDtdDataSet.write(dataSet,new FileOutputStream("dbunit1.dtd"));
	}

 生成的dbunit.xml内容如下: 

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
  <student Id="0001" name="翁仔" sex="m" birthday="1979-12-31"/>
  <student Id="0002" name="王翠花" sex="f" birthday="1982-08-09"/>
  <users id="1" username="zhangsan" password="123"/>
  <users id="2" username="lisi" password="456"/>
  <users id="3" username="wangwu" password="789"/>
</dataset>

 2.用dbunit做测试,需要继承DBTestCase,并需要重写protected IDataSet getDataSet() throws Exception 

package com.chenjo.expa;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.dbunit.Assertion;
import org.dbunit.DBTestCase;
import org.dbunit.PropertiesBasedJdbcDatabaseTester;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.SortedTable;
import org.dbunit.dataset.filter.DefaultColumnFilter;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
public class SimpleTest extends DBTestCase {
	private File file = null;
	public SimpleTest()
	{
//		super();
		System.setProperty(
				PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
				"com.mysql.jdbc.Driver");
		System.setProperty(
				PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
				"jdbc:mysql://localhost/test");
		System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
				"root");
		System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
				"root");
	}
	
	/**
	 * 给定数据集
	 */
	@Override
	protected IDataSet getDataSet() throws Exception {
		System.out.println("init...");
		return new FlatXmlDataSet(new FileInputStream("dbunit.xml"));
	}
	
	public void test1() throws Exception{
		IDataSet dbDataSet = getConnection().createDataSet();
		ITable dbTable = dbDataSet.getTable("users");
		
		IDataSet xmlDataSet = new FlatXmlDataSet(new FileInputStream("dbunit.xml"));
		ITable xmlTable = xmlDataSet.getTable("users");
		
		Assertion.assertEquals(xmlTable, dbTable);
	}
	/**
	 * 表结构和dbunit1.xml结构不一致
	 */
	public void test2() throws Exception{
		IDataSet dbDataSet = getConnection().createDataSet();
		ITable dbTable = dbDataSet.getTable("users");
		
		IDataSet xmlDataSet = new FlatXmlDataSet(new FileInputStream("dbunit1.xml"));
		ITable xmlTable = xmlDataSet.getTable("users");
		//第一种写法
//		dbTable = DefaultColumnFilter.includedColumnsTable(dbTable,xmlTable.getTableMetaData().getColumns());
		//第二种写法
		dbTable = DefaultColumnFilter.includedColumnsTable(dbTable,xmlDataSet.getTableMetaData("users").getColumns());
		
		Assertion.assertEquals(xmlTable, dbTable);
	}
	/**
	 * 只比较username
	 */
	public void test3() throws Exception{
		IDataSet dbDataSet = getConnection().createDataSet();
		ITable dbTable = dbDataSet.getTable("users");
		
		IDataSet xmlDataSet = new FlatXmlDataSet(new FileInputStream("dbunit1.xml"));
		ITable xmlTable = xmlDataSet.getTable("users");
		
		dbTable = DefaultColumnFilter.excludedColumnsTable(dbTable, new String[]{"id","password"});
		xmlTable = DefaultColumnFilter.excludedColumnsTable(dbTable, new String[]{"password"});
		
		Assertion.assertEquals(xmlTable, dbTable);
	}
	/**
	 * 表里数据和dbunit2.xml里的数据的顺序不一致
	 */
	public void test4() throws Exception{
		IDataSet dbDataSet = getConnection().createDataSet();
		ITable dbTable = dbDataSet.getTable("users");
		
		IDataSet xmlDataSet = new FlatXmlDataSet(new FileInputStream("dbunit2.xml"));
		ITable xmlTable = xmlDataSet.getTable("users");
		
		SortedTable dbSortedTable = new SortedTable(dbTable,new String[]{"id"});
		//按数据库里表结构字段类型来进行排序,如果是int则按int排序,不是依照字符串的形式排序
		dbSortedTable.setUseComparable(true);
		
		SortedTable xmlSortedTable = new SortedTable(xmlTable,new String[]{"id"});
		//按数据库里表结构字段类型来进行排序,如果是int则按int排序,不是依照字符串的形式排序
		xmlSortedTable.setUseComparable(true);
		
		Assertion.assertEquals(xmlSortedTable, dbSortedTable);
	}
	
	/**
	 * 对Users表插入一条记录做测试
	 * @throws Exception
	 */
	public void test5() throws Exception{
		UsersDAO db = new UsersDAO();

		User user = new User();
		user.setId(9);
		user.setUsername("hello");
		user.setPassword("world");

		db.save(user);

		IDataSet dataSet = getConnection().createDataSet();
		ITable actualTable = dataSet.getTable("users");

		IDataSet dataSet2 = new FlatXmlDataSet(new File("expected.xml"));
		ITable expectedTable = dataSet2.getTable("users");

		Assertion.assertEquals(expectedTable, actualTable);
	}
	
	/**
	 * 在把xml里的数据导入到db里之前,需要对数据库里的表的数据做的操作。
	 */
	protected DatabaseOperation getSetUpOperation() throws Exception
    {
		
		// 连接DB 
		Connection conn=getMySqlConnection();
		// 获得DB 连接
		IDatabaseConnection connection = connection =new DatabaseConnection(conn);
		// 对数据库中的操作对象表student 进行备份
		QueryDataSet backupDataSet = new QueryDataSet(connection);
		backupDataSet.addTable("student");
		file=File.createTempFile("student_back",".xml");// 备份文件
		FlatXmlDataSet.write(backupDataSet,new FileOutputStream(file));
		// 准备数据的读入
		IDataSet dataSet = new FlatXmlDataSet( new FileInputStream("dbunit.xml"));
		System.out.println("setup...");
		DatabaseOperation.CLEAN_INSERT.execute(connection,dataSet);
        return DatabaseOperation.NONE;
    }
	/**
	 * 测试执行完以后,需要对数据库里的表里的数据做的操作
	 */
    protected DatabaseOperation getTearDownOperation() throws Exception
    {
    	Connection conn=getMySqlConnection();
    	IDatabaseConnection connection =new DatabaseConnection(conn);
		IDataSet dataSet = new FlatXmlDataSet(file);
		DatabaseOperation.CLEAN_INSERT.execute(connection,dataSet);
    	System.out.println("teardown...");
        return DatabaseOperation.NONE;
    }

	Connection getMySqlConnection() {
		// 驱动程序名
		String driver = "com.mysql.jdbc.Driver";

		// URL指向要访问的数据库名test
		String url = "jdbc:mysql://127.0.0.1:3306/test";

		// MySQL配置时的用户名
		String user = "root";

		// MySQL配置时的密码
		String password = "root";

		Connection conn = null;
		// 加载驱动程序
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, password);

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return conn;

	}
}

 其中expected.xml内容为: 

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
  <person/>
  <users id="1" username="zhangsan" password="123"/>
  <users id="2" username="lisi" password="456"/>
  <users id="3" username="wangwu" password="789"/>
  <users id="9" username="hello" password="world"/>
</dataset>

 

补充说明:

数据库test的编码格式: utf-8

expected.xml:  以 UTF-8 无BOM格式编码 (Notepadd++)

你可能感兴趣的:(dbunit,集成测试)