在我之前的博文Junit5中實(shí)現(xiàn)參數(shù)化測(cè)試中,我們提到過,Junit5能夠使用CsvFileSource參數(shù)源來實(shí)現(xiàn)外部數(shù)據(jù)的引入并作為參數(shù)傳遞給測(cè)試方法。
但實(shí)際應(yīng)用中我們經(jīng)常使用excel文件來保存測(cè)試數(shù)據(jù)或進(jìn)行數(shù)據(jù)驅(qū)動(dòng)。
今天就介紹下如何通過junit5的參數(shù)化方法,來支持Excel文件的參數(shù)化
MethodSource
Junit5當(dāng)中新增的ParameterizedTest注解,可以在對(duì)應(yīng)的測(cè)試方法中攜帶參數(shù),并且支持多種參數(shù)源,參見前文Junit5中實(shí)現(xiàn)參數(shù)化測(cè)試。
而其中的MethodResource方法可以自己定義一個(gè)參數(shù)實(shí)現(xiàn)方法
這里MethodSource所使用的參數(shù)方法有幾個(gè)要求:
- 返回Stream<Arguments>參數(shù)流或集合類型的的參數(shù)集
- 靜態(tài)引用
- 本身不攜帶參數(shù)
這就給我們自行擴(kuò)展通過Excel數(shù)據(jù)驅(qū)動(dòng)提供了入口。
如我們定義一個(gè)測(cè)試用例,使用參數(shù)化方法,通過MethodSource使用ExcelMethod參數(shù)方法傳入?yún)?shù)。代碼如:
@ParameterizedTest
@MethodSource("ExcelMethod")
public void qiucaoTest(String person, int age, float salary){
System.out.println(person + " " + age +" "+ salary);
}
但是因?yàn)镸ethodSource方法的調(diào)用限制,本身不能攜帶參數(shù),所以如果我們希望指定使用的Excel文件路徑,以及具體的數(shù)據(jù)表Sheet。還必須進(jìn)行一層擴(kuò)展。ExcelMethod方法定義如下:
static Stream<Arguments> ExcelMethod() {
return getTestDataStreamFromExcelFile(".\\src\\test\\demoData.xlsx","Sheet1");
}
POI庫處理excel文件
ExcelMethod中我們定義了一個(gè)處理Excel文件的通用方法。這里可以使用通用的第三方Office文件處理庫POI
使用POI可以通過maven導(dǎo)入。這里主要有poi和ooxml兩個(gè)依賴庫需要使用
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
引入POI后就可以利用POI提供的便利的excel數(shù)據(jù)處理功能,完成數(shù)據(jù)的讀取
public static Stream<Arguments> getTestDataStreamFromExcelFile(String excelFullPath,
String sheetName){
Stream<Arguments> returnStream = Stream.empty();
//定義單元格數(shù)據(jù)格式處理對(duì)象
DataFormatter myDataFormatter = new DataFormatter();
//獲取工作簿對(duì)象
try(Workbook excelFile = WorkbookFactory.create(new File(excelFullPath),null,true)) {
//獲取工作表
Sheet excelSheet1 = excelFile.getSheet(sheetName);
//行數(shù)據(jù)處理,忽略標(biāo)題行,行數(shù)據(jù)作為后續(xù)參數(shù)List
for(Row row: excelSheet1){
if(row.getRowNum()==0) {continue;}
ArrayList<Object> rowArrayList = new ArrayList<>();
//獲取單元格數(shù)值,存入行List
for (Cell cell : row) {
rowArrayList.add(myDataFormatter.formatCellValue(cell));
}
//轉(zhuǎn)換為MethodSource的Arguments對(duì)象
Arguments arguments = Arguments.of(rowArrayList.toArray());
//Arguments轉(zhuǎn)換為Stream
returnStream = Stream.concat(returnStream,Stream.of(arguments));
}
return returnStream;
} catch (IOException e) {
e.printStackTrace();
}
return returnStream;
}
如此,我們就完成了通過Excel在Junit5中進(jìn)行數(shù)據(jù)驅(qū)動(dòng)測(cè)試的支持。
思考:我們的測(cè)試方法,現(xiàn)在需要匹配Excel數(shù)據(jù),進(jìn)行參數(shù)的個(gè)數(shù)和類型的匹配指定,有沒有更好的方法可以更加靈活地兼容Excel數(shù)據(jù)內(nèi)容呢?
歡迎關(guān)注后續(xù)更新