快速上手
Springboot 添加 DBunit 依赖
// https://mvnrepository.com/artifact/org.dbunit/dbunit
testCompile group: 'org.dbunit', name: 'dbunit', version: '2.5.4'
编写Test.java
import org.dbunit.DBTestCase;
import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
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.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DBunit extends DBTestCase {
@Resource
DataSource dataSource;
IDatabaseConnection iDatabaseConnection;
@Override
protected IDataSet getDataSet() throws Exception {
return iDatabaseConnection.createDataSet();
}
@Before
public void before() throws Exception{
iDatabaseConnection = new DatabaseConnection(dataSource.getConnection());
}
}
将数据库数据转换为FlatXml
@Test
public void testPartialExport() throws DataSetException, IOException {
QueryDataSet queryDataSet = new QueryDataSet(iDatabaseConnection);
queryDataSet.addTable("user", "select * from user");
FlatXmlDataSet.write(queryDataSet, new FileOutputStream("user.xml"));
}
执行后,将会得到一个user.xml文件,里面记录了数据库user表的所有数据,看起来大概是这个样子
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<user id="1" username="mechanists" password="ABA3FC1EB2997E318E43CA099AE175CA"/>
<user id="2" username="reporter" password="ABA3FC1EB2997E318E43CA099AE175CA" />
</dataset>