51Testing软件测试论坛
标题:
DBunit about
[打印本页]
作者:
hust88
时间:
2010-4-26 17:04
标题:
DBunit about
package test.sample.service.util;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import org.dbunit.DatabaseTestCase;
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;
/**
* DbUnit 可以有不同的数据库操作,我使用了其中的两种:
*DELETE_ALL ,它删除表中所有行。
*CLEAN_INSERT ,它删除表中所有行并插入数据集提供的行。
*This method inserts the contents of a FlatXmlDataSet file
*into the connection
* @author donganlei
*
*/
public class TestDBConnection extends DatabaseTestCase {
private IDatabaseConnection conn;
private String driverName = "oracle.jdbc.OracleDriver";
private String dburl = "jdbc
racle:thin
192.168.0.2:1521
ORTAL";
private String username = "portal";
private String pwd = "portal";
private String schema = "
ORTAL";
private String xmlUrl = "e:\\test.xml";//从数据库中取值到XML中(路径)
private String dbxmlurl = "e:\\test.xml";//从XML中还原数据库中的记录(路径)
/**
* 初始化TestDBConnection
*
*/
public TestDBConnection() {
try {
Class.forName(driverName);
Connection jdbcConnection = DriverManager.getConnection(dburl,
username, pwd);
conn = new DatabaseConnection(jdbcConnection, schema);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 建立连接
* 返回IDatabaseConnection
*/
public synchronized IDatabaseConnection getConnection() throws Exception {
Class.forName(driverName);
Connection jdbcConnection = DriverManager.getConnection(dburl,
username, pwd);
conn = new DatabaseConnection(jdbcConnection, schema);
return conn;
}
/**
* 方法:它删除表中所有行并插入数据集提供的行
* @throws Exception
*/
protected void insertFileIntoDb() throws Exception
{
DatabaseOperation.CLEAN_INSERT.execute(getConnection(), getDataSet());
}
/**
* 方法:删除数据库中的所有数据
* @throws Exception
*/
protected void deleteFileDb()throws Exception{
DatabaseOperation.DELETE_ALL.execute(conn, getDataSet());
}
/**
* 方法 :从XML中读取数据
*/
protected IDataSet getDataSet() throws Exception {
return new FlatXmlDataSet(new FileInputStream(dbxmlurl));
}
/**
* 方法:读取数据库中的内容到xmlUrl中
* @param tableNames
* @throws Exception
*/
public void backUp(String[] tableNames) throws Exception {
IDataSet fullDataSet = conn.createDataSet(tableNames);
FlatXmlDataSet.write(fullDataSet, new FileOutputStream(xmlUrl));
}
/**
* 方法:还原数据库中的数据
*
*/
public void overRead() {
}
/**
* 方法关闭连接
* @throws Exception
*/
public void closeConn()throws Exception{
conn.close();
}
}
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/)
Powered by Discuz! X3.2