亲宝软件园·资讯

展开

SpringBoot DBunit使用 Spring Boot 与DBunit 配合使用方法

170901 人气:3

本文介绍了Spring Boot 与DBunit 配合使用方法,分享给大家,具体如下:

DBUnit

快速上手

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>

IDataSet

官网文档地址

加载全部内容

相关教程
猜你喜欢
用户评论