日期:2014-05-16 浏览次数:20407 次
<dependency> <groupId>org.dbunit</groupId> <artifactId>dbunit</artifactId> <version>2.4.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> <scope>compile</scope> </dependency>
<?xml version="1.0" encoding="UTF-8"?> <dataset> <!-- 注意,此处的user代表表名(database table name) --> <user id="1" username="123" password="456"/> <user id="2" username="123" password="456"/> <user id="3" username="123" password="456"/> <user id="4" username="123" password="456"/> <user id="5" username="123" password="456"/> </dataset>
package com.accentrix.ray; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import javax.sql.DataSource; import org.dbunit.database.DatabaseDataSourceConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.database.QueryDataSet; import org.dbunit.dataset.DataSetException; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.dbunit.dataset.xml.FlatXmlProducer; import org.dbunit.operation.DatabaseOperation; import org.junit.AfterClass; import org.junit.BeforeClass; import org.xml.sax.InputSource; public class BaseTest { public static IDatabaseConnection connection; public static DataSource dataSource; private File temp; @BeforeClass public static void init() throws Exception { // 通过DataSource获取DataBaseSourceConnection connection = new DatabaseDataSourceConnection(dataSource); } @AfterClass public static void destroy() throws Exception { if (connection != null) { connection.close(); } } protected IDataSet getDataSet(String name) throws DataSetException { // 通过类加载器获取default-data.xml文件的内容 InputStream is = this.getClass().getClassLoader() .getResourceAsStream(name + ".xml"); // IDataSet就类似是一个数据的容器,把default-data.xml内容 // 转换成了DBUnit可识别的数据返回出去 return new FlatXmlDataSet(new FlatXmlProducer(new InputSource(is))); } protected void backupAll() throws Exception { // createDataSet代表从数据库中获取到DataSet,此时DataSet为数据库的内容 IDataSet ds = connection.createDataSet(); // 创建临时文件 temp = File.createTempFile("temp", "xml"); // 将数据库内容的DataSet写入临时文件当中 F