1 . 概念
DbUnit是为数据库驱动的项目提供的一个对JUnit 的扩展,除了提供一些常用功能,它可以将你的数据库置于一个测试轮回之间的状态。
2 . Maven集成DBUnit
2.1 导包
<!-- dbunit -->
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.5.0</version>
</dependency>
<!-- logback-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
2.2 创建数据文件夹
1)创建dbunit文件夹。存放dbunit所有数据信息
2)在dbunit文件夹下创建backup文件夹。存放数据库备份数据文件
3)创建test文件夹。存放所有测试数据文件
2.3 代码整理
2.3.1 DBUnitBase基类
DBUnit说明:
1)设置数据库连接信息
2)设置数据库数据备份路径
3)设置测试数据文件路径
4)数据备份方法和数据恢复方法
package com.zzwx.test.dbunit.base;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.DatabaseDataSet;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
publicabstractclass DBUnitBase {
protected Connection conn = null;
protected IDatabaseConnection connection = null;
protected String backupDataPath = "src/test/resources/dbunit/backup/";
protected String testDataPath = "src/test/resources/dbunit/test/";
protected File file = null;
protected List<File> files = null;
protected Connection getConnection() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
// 连接DB
Connectionconn = DriverManager
.getConnection(
"jdbc:mysql://localhost:3306/zzwx?useUnicode=true&characterEncoding=UTF-8",
"root", "123456");
returnconn;
}
protectedvoid backupData(String tableName, String backupFileName)
throws Exception {
try {
conn =getConnection();
connection = new DatabaseConnection(conn);
if (null != tableName && !"".equals(tableName)) {
// 通过表名备份单张表单数据
QueryDataSetbackupDataSet = new QueryDataSet(connection);
backupDataSet.addTable(tableName);
// 设置备份文件路径
file = new File(backupDataPath + backupFileName);
FlatXmlDataSet.write(backupDataSet, new FileWriter(file),
"UTF-8");
}else {
// 备份数据库所有数据
IDataSetbackupDataSet = new DatabaseDataSet(connection, true);
// 设置备份文件路径
file = new File(backupDataPath + backupFileName);
FlatXmlDataSet.write(backupDataSet, new FileWriter(file),
"UTF-8");
}
}catch (Exception e) {
e.printStackTrace();
}finally {
closeCon();
}
}
@SuppressWarnings("deprecation")
publicvoid recoverData(File file) {
try {
conn =getConnection();
connection = new DatabaseConnection(conn);
IDataSetdataSet = new FlatXmlDataSet(file);
DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
}catch (Exception e) {
e.printStackTrace();
}finally {
closeCon();
}
}
protectedvoid closeCon() {
try {
if (connection != null) {
connection.close();
}
if (conn != null) {
conn.close();
}
}catch (SQLException e) {
e.printStackTrace();
}
}
}
2.3.2 DBUnitAll
DBUnitAll说明:
1)继承DBUnitBase基类
2)添加测试数据,并将测试前数据备份到src/test/resources/dbunit/backup/all_data_back.xml
3)备份数据库所有数据方法、恢复数据库数据方法
4)使用该类时,setUpBackupAll(fileName)和recoverAllData()方法需要成对调用。不然数据库数据不会恢复到测试之前的数据。
package com.zzwx.test.dbunit;
import java.io.FileInputStream;
import java.sql.Connection;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import com.zzwx.test.dbunit.base.DBUnitBase;
publicclass DBUnitAll extends DBUnitBase {
@SuppressWarnings("deprecation")
publicvoid setUpBackupAll(String fileName) {
// JDBC数据库连接
Connectionconn = null;
// DBUnit数据库连接
IDatabaseConnectionconnection = null;
try {
conn =getConnection();
// 获得DB连接
connection = new DatabaseConnection(conn);
// 备份数据库测试之前的数据
backupAll();
// 准备数据的读入
IDataSetdataSet = new FlatXmlDataSet(new FileInputStream(
testDataPath + fileName));
connection.createDataSet(new String[] {});
DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
}catch (Exception e) {
e.printStackTrace();
}finally {
closeCon();
}
}
publicvoid backupAll() {
try {
super.backupData(null, "all_data_back.xml");
}catch (Exception e) {
e.printStackTrace();
}
}
publicvoid recoverAllData() {
super.recoverData(file);
}
}
2.3.3 DBUnitEach
DBUnitEach说明 :
1) 继承DBUnitBase基类
2) 添加测试数据,并备份需要备份数据表的数据,通过表名备份数据,每张表对于一个备份数据文件
setUpBackupEach()和recoverBackupEach()需要成对出现。不然数据库数据不会恢复到测试之前的数据。
package com.zzwx.test.dbunit;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.ArrayList;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import com.zzwx.test.dbunit.base.DBUnitBase;
publicclass DBUnitEach extends DBUnitBase {
@SuppressWarnings("deprecation")
publicvoid setUpBackupEach(String fileName, String... tableNames) {
// JDBC数据库连接
Connectionconn = null;
// DBUnit数据库连接
IDatabaseConnectionconnection = null;
try {
conn =getConnection();
// 获得DB连接
connection = new DatabaseConnection(conn);
// 备份数据库测试之前的数据
backupDataEach(tableNames);
// 准备数据的读入
IDataSetdataSet = new FlatXmlDataSet(new FileInputStream(
testDataPath + fileName));
connection.createDataSet(new String[] {});
DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
}catch (Exception e) {
e.printStackTrace();
}finally {
closeCon();
}
}
publicvoid backupDataEach(String... tableNames) throws Exception {
try {
if (tableNames != null && tableNames.length > 0) {
files = new ArrayList<File>();
for (String tableName : tableNames) {
super.backupData(tableName, tableName + "_back.xml");
files.add(file);
}
}
}catch (Exception e) {
e.printStackTrace();
}finally {
closeCon();
}
}
publicvoid recoverBackupEach() {
if (null != files && files.size() > 0) {
for (File file : files) {
super.recoverData(file);
}
}
}
}
2.3.4 DBUnitEachAll
DBUnitEachAll说明:
1) 继承DBUnitBase基类
2) 添加测试数据,并备份所有要备份数据表的所有数据到一个备份文件中each_all_data_back.xml
3) setUpBackupEachAll()和recoverBackupEachAll()方法成对出现。不然数据库数据不会恢复到测试之前的数据。
package com.zzwx.test.dbunit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.sql.Connection;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import com.zzwx.test.dbunit.base.DBUnitBase;
publicclass DBUnitEachAll extends DBUnitBase {
@SuppressWarnings("deprecation")
publicvoid setUpBackupEachAll(String fileName, String... tableNames) {
// JDBC数据库连接
Connectionconn = null;
// DBUnit数据库连接
IDatabaseConnectionconnection = null;
try {
conn =getConnection();
// 获得DB连接
connection = new DatabaseConnection(conn);
// 备份数据库测试之前的数据
backupDataEachAll(tableNames);
// 准备数据的读入
IDataSetdataSet = new FlatXmlDataSet(new FileInputStream(
testDataPath + fileName));
connection.createDataSet(new String[] {});
DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
}catch (Exception e) {
e.printStackTrace();
}finally {
closeCon();
}
}
publicvoid backupDataEachAll(String... tableNames) throws Exception {
try {
conn =getConnection();
// 获得DB连接
connection = new DatabaseConnection(conn);
QueryDataSetbackupDataSet = new QueryDataSet(connection);
if (null != tableNames && tableNames.length > 0) {
for (String tableName : tableNames) {
backupDataSet.addTable(tableName);
}
}
// 设置备份文件路径
file = new File(backupDataPath + "each_all_data_back.xml");
FlatXmlDataSet.write(backupDataSet, new FileWriter(file), "UTF-8");
}catch (Exception e) {
e.printStackTrace();
}finally {
closeCon();
}
}
publicvoid recoverBackupEachAll(){
if(null != file){
super.recoverData(file);
}
}
}