自动化测试框架-数据读取
1.准备数据:数据格式为{json},放在json文件内,例如这样:
2.工具类:读取.json文件,保存在Map<testCaseName,JSONObject>内
public class FileUtil {
public static Map<String, JSONObject> jsonToSearchFilter(String fileName) throws IOException, IOException {
Map<String, JSONObject> result = new HashMap<>();
StringBuffer buffer = new StringBuffer();
String dataPath = "" + fileName;
BufferedReader br = new BufferedReader(new FileReader(new File(dataPath)));
String line = "";
// 每次读一行,将[{},{}]的字符都读到一个StringBuffer内
while ((line = br.readLine()) != null) {
buffer.append(line);
}
String jsonData = buffer.toString();
try {
//将json格式的字符串转换成JSONOArray对象
JSONArray array = JSONObject.parseArray(jsonData);
for (int i = 0; i < array.size(); i++) {
// 解析JSONArray,将里边的JSONObject都添加到map内,map的key就是JSONObject的testCaseName
JSONObject jsonObj = (JSONObject) array.get(i);
String testCaseName = jsonObj.getString("testCaseName");
result.put(testCaseName, jsonObj);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) throws IOException {
Map<String,JSONObject> mp = jsonToSearchFilter("bankApply.json");
JSONObject data = mp.get("G_BankApplyTest");
System.out.println(data.getJSONObject("data"));
}
}
3.
3.1在init类里初始化数据:
public Map<String, JSONObject> testData = new HashMap<>(); testData = DataUtils.jsonToSearchFilter("fileName.json");
3.2 测试用例类继承init类,在具体测试方法里找到具体的数据:content
data = testData.get("key"); // HashMap.get(key),返回该key(testCaseName)对应的jsonObject content = data.getJSONObject("data");