testng的功能很强大,利用@DataProvider可以做数据驱动,数据源文件可以是EXCEL,XML,YAML,甚至可以是TXT文本。在这以yaml为例:
备注:@DataProvider的返回值类型只能是Object[][]与Iterator[]
application.yaml:
user:
name: xiaoqiang
passwd: "1236454"
user1:
name: xiaohong
passwd: "1238309"
user2:
name: rongrong
passwd: "908344s"
user3:
name: lisi
passwd: "123566s"
解析yaml文件,然后把解析出来的list转换成Object[][]类型的数据,且结合在@DataProvider中。
YamlDataHelper.java文件
importorg.testng.annotations.DataProvider;importorg.yaml.snakeyaml.Yaml;importjava.io.FileInputStream;importjava.net.URL;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;public classYamlDataHelper {private static List>getYamlList() {
List> list = newArrayList();
Map> map =readYamlUtil();for (Map.Entry>me : map.entrySet()) {
Map numNameMapValue =me.getValue();
Map tmp = new HashMap<>();for (Map.EntrynameMapEntry : numNameMapValue.entrySet()) {
String numKey=nameMapEntry.getKey();
String nameValue=nameMapEntry.getValue();
tmp.put(numKey, nameValue);
}
list.add(tmp);
}returnlist;
}public static Map>readYamlUtil() {
Map> map = null;try{
Yaml yaml= newYaml();
URL url= YamlDataHelper.class.getClassLoader().getResource("application.yaml");if (url != null) {//获取yaml文件中的配置数据,然后转换为Map
map = yaml.load(newFileInputStream(url.getFile()));returnmap;
}
}catch(Exception e) {
e.printStackTrace();
}returnmap;
}
@DataProviderpublicObject[][] yamlDataMethod() {
List> yamlList =getYamlList();
Object[][] files= newObject[yamlList.size()][];for (int i = 0; i < yamlList.size(); i++) {
files[i]= newObject[]{yamlList.get(i)};
}returnfiles;
}
}
再通过测试文件来测试一下:
TestYamlData.java文件:
importorg.testng.annotations.Test;importjava.util.Map;public class TestYamlData extendsYamlDataHelper{
@Test(dataProvider= "yamlDataMethod")public void testYamlData(Mapparam){
System.out.println(param.get("name")+"\t"+param.get("passwd"));
}
}
运行结果如下:
[TestNG] Running:
C:\Users\Administrator\.IntelliJIdea2018.2\system\temp-testng-customsuite.xml
xiaoqiang1236454xiaohong1238309rongrong 908344s
lisi 123566s===============================================Default Suite
Total tests run:4, Failures: 0, Skips: 0
===============================================Picked up JAVA_TOOL_OPTIONS:-Dfile.encoding=UTF-8Process finished with exit code0