1.实现目标
常用变量解析到map,方便后面解析初始化sql或者入参的时候对变量进行替换
2.添加工具类
VariableUtil.java
package com.syq.autotest.utils;import com.syq.autotest.entity.Variable;
import org.apache.log4j.Logger;import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;/*** @description* @author: Admin* @create: 2024/2/28 14:38*/
public class VariableUtil {public static Logger logger = Logger.getLogger(VariableUtil.class);// 存放变量和值的mappublic static Map<String, String> variableMap = new HashMap<String, String>();// 从对象列表variableList中获取变量和值,放到map中public static void loadVariablesToMap(List<Variable> variableList) {for (Variable variable : variableList){String name = variable.getName();String value = variable.getValue();variableMap.put(name,value);}}// 替换变量public static String variableSubstitution(String parameters) {// 获取所有变量名Set<String> names = variableMap.keySet();for (String name : names) {if (parameters.contains(name)){parameters = parameters.replace(name,variableMap.get(name));}}return parameters;}
}
3.修改@BeforeTest修饰的方法
调用VariableUtil工具类中方法(在BaseCase.java中)
@Parameters({ "excelPath", "dataSheetName", "variableSheetName"})@BeforeTestpublic void readDataFromExcel(@Optional("caseData/caseData-解决韧.xlsx") String excelPath, @Optional("case") String dataSheetName, @Optional("variables") String variableSheetName){logger.info("excelPath: " + excelPath);logger.info("dataSheetName: " + dataSheetName);logger.info("variableSheetName: " + variableSheetName);cases = ExcelUtil.loadExcel(excelPath, dataSheetName, CaseData.class);variables = ExcelUtil.loadExcel(excelPath, variableSheetName, Variable.class);// logger.info("读取文件获取到的cases对象:" + cases);// logger.info("读取文件获取到的variables对象:" + variables);VariableUtil.loadVariablesToMap(variables);Set<String> keys = VariableUtil.variableMap.keySet();for (String key : keys) {System.out.println(key + "=" + VariableUtil.variableMap.get(key));}}
4.结果演示
运行xml
通过结果可以看到,常用变量放到了map中
如需要代码,可在资源中自行下载,如有其他问题,可在评论区评论!!!