本文介紹了spring boot 與dbunit 配合使用方法,分享給大家,具體如下:
快速上手
springboot 添加 dbunit 依賴
1
2
|
// https://mvnrepository.com/artifact/org.dbunit/dbunit testcompile group: 'org.dbunit' , name: 'dbunit' , version: '2.5.4' |
編寫test.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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()); } } |
將數(shù)據(jù)庫數(shù)據(jù)轉(zhuǎn)換為flatxml
1
2
3
4
5
6
|
@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" )); } |
執(zhí)行后,將會(huì)得到一個(gè)user.xml文件,里面記錄了數(shù)據(jù)庫user表的所有數(shù)據(jù),看起來大概是這個(gè)樣子
1
2
3
4
5
6
|
<?xml version= '1.0' encoding= 'utf-8' ?> <dataset> <user id= "1" username= "mechanists" password= "aba3fc1eb2997e318e43ca099ae175ca" /> <user id= "2" username= "reporter" password= "aba3fc1eb2997e318e43ca099ae175ca" /> </dataset> |
idataset
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000016337648