java结合testng,利用yaml做数据源的数据驱动实例

testng的功能很强大,利用@DataProvider可以做数据驱动,数据源文件可以是EXCEL,XML,YAML,甚至可以是TXT文本。在这以yaml为例:

备注:@DataProvider的返回值类型只能是Object[][]与Iterator<Object>[]

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文件

import org.testng.annotations.DataProvider;
import org.yaml.snakeyaml.Yaml; import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class YamlDataHelper { private static List<Map<String, String>> getYamlList() {
List<Map<String, String>> list = new ArrayList();
Map<String, Map<String, String>> map = readYamlUtil();
for (Map.Entry<String, Map<String, String>> me : map.entrySet()) {
Map<String, String> numNameMapValue = me.getValue();
Map<String, String> tmp = new HashMap<>();
for (Map.Entry<String, String> nameMapEntry : numNameMapValue.entrySet()) {
String numKey = nameMapEntry.getKey();
String nameValue = nameMapEntry.getValue();
tmp.put(numKey, nameValue);
}
list.add(tmp);
}
return list;
} public static Map<String, Map<String, String>> readYamlUtil() {
Map<String, Map<String, String>> map = null;
try {
Yaml yaml = new Yaml();
URL url = YamlDataHelper.class.getClassLoader().getResource("application.yaml");
if (url != null) {
//获取yaml文件中的配置数据,然后转换为Map
map = yaml.load(new FileInputStream(url.getFile()));
return map;
}
} catch (Exception e) {
e.printStackTrace();
}
return map; } @DataProvider
public Object[][] yamlDataMethod() {
List<Map<String, String>> yamlList = getYamlList();
Object[][] files = new Object[yamlList.size()][];
for (int i = 0; i < yamlList.size(); i++) {
files[i] = new Object[]{yamlList.get(i)};
}
return files;
} }

再通过测试文件来测试一下:

TestYamlData.java文件:

import org.testng.annotations.Test;

import java.util.Map;

public class TestYamlData extends YamlDataHelper{

    @Test(dataProvider = "yamlDataMethod")
public void testYamlData(Map<String,String> param){
System.out.println(param.get("name")+"\t"+param.get("passwd"));
}
}

运行结果如下:

[TestNG] Running:
C:\Users\Administrator\.IntelliJIdea2018.2\system\temp-testng-customsuite.xml
xiaoqiang 1236454
xiaohong 1238309
rongrong 908344s
lisi 123566s ===============================================
Default Suite
Total tests run: 4, Failures: 0, Skips: 0
=============================================== Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 Process finished with exit code 0
上一篇:Dream_Spark-----Spark 定制版:004~Spark Streaming事务处理彻底掌握


下一篇:NYOJ--703