软件测试学习之路

Java实现读取Excel中的Http请求及提取数组参数、文字转

2018-01-15  本文已影响9人  乘风破浪的姐姐

在 Java实现读取Excel中的Http请求及检查点、关联API (一) 中,实现了检查点、单个参数关联等功能API。

项目场景

这里需要实现的场景:
1、多个参数关联,如:数组参数的提取。
2、只执行有效的testcase
3、读取excel中标识时,利用转换器,转换成boolean类型。
4、将测试结果写入excel中时,将boolean类型的标识转换成汉字。
5、每次生成的测试结果excel内容不覆盖
6、将测试结果excel发送到指定邮箱

(1)、提取数组参数传递到需要用到的关联处

修改SaveParamsUtil类:

public class SaveParamsUtil {
    private  static  Map<String,Object> paramsMap = new HashMap<String,Object>();
    public static void saveParamsToMap(String json,String params){
        Map<String,Object> map = MapUtil.StringToMap(params);
        if(map!=null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue().toString();
                if(key.endsWith("*")){
                   List<Object> list =  JsonPath.read(json,val);
                   String nodekey = key.split("_")[0];
                        for(int i=0;i<list.size();i++){
                           String k = nodekey + "_g" + (i+1);
                           String v = list.get(i).toString();
                           paramsMap.put(k, v);
                           System.out.println(k+"-------"+v);
                        }

                }else{
                    Object obj = JsonPath.read(json, val);
                    paramsMap.put(key, obj.toString());
                }
            }
        }
    }

    public static Object get(String key){
        return  paramsMap.get(key);
    }
}
(2)、执行有效case,读取excel中有效/无效标识时,利用转换器,转换成boolean类型。将测试结果写入excel中时,将boolean类型的标识转换成汉字。

excel中内容如下:


image.png

TestCase中新增属性validFlag

@ExcelField(title = "是否有效",order = 1,readConverter = IsValidReadConvert.class,writeConverter = IsValidWriteConvert.class)
    private boolean validFlag;

    public boolean isValidFlag() {
        return validFlag;
    }

    public void setValidFlag(boolean validFlag) {
        this.validFlag = validFlag;
    }

新增IsValidReadConvert类,用于读取excel时对是否有效validFlag转换成boolean类型

import com.github.crab2died.converter.ReadConvertible;
public class IsValidReadConvert implements ReadConvertible {
    @Override
    public Object execRead(String s) {
        if("有效".equals(s)){
            return true;
        }else {
            return false;
        }
    }
}

新增IsValidWriteConvert类,用于将测试结果写入excel中时,将boolean类型的标识转换成汉字。

import com.github.crab2died.converter.WriteConvertible;
public class IsValidWriteConvert implements WriteConvertible {
    @Override
    public Object execWrite(Object o) {
        boolean flag =(Boolean)o;
        return flag==true?"有效":"无效";
    }
}

在ApiTest测试类中,需要修改如下:

  public static void main(String[] args) throws Exception {
        String path = System.getProperty("user.dir")+ File.separator+"data"+File.separator+"apitest.xlsx";
        List<TestCase> list = ExcelUtils.getInstance().readExcel2Objects(path,TestCase.class);
        if(list!=null){
            for(TestCase testCase : list){
                if(testCase.isValidFlag()){
                    PatternUtil.matcherParams(testCase);
                    String responseJson =null;
                    if("get".equals(testCase.getType())){
                        responseJson = HttpUtils.doGet(testCase.getUrl(), MapUtil.StringToMap(testCase.getHeader()));
                    }else if("post".equals(testCase.getType())){
                        responseJson = HttpUtils.doPost(testCase.getUrl(), MapUtil.StringToMap(testCase.getParams(),"&"),MapUtil.StringToMap(testCase.getHeader()));
                    }else  if("postjson".equals(testCase.getType())){
                        responseJson = HttpUtils.doPostJson(testCase.getUrl(), testCase.getParams(),MapUtil.StringToMap(testCase.getHeader()));
                    }
                    Boolean checkFlag =  CheckPointUtil.checkPoint(responseJson,testCase.getCheckP());
                    System.out.println("checkFlag="+checkFlag);
                    if(checkFlag){
                        SaveParamsUtil.saveParamsToMap(responseJson,testCase.getCorrelation());
                        testCase.setResult("测试通过");
                    }else{
                        testCase.setResult("测试失败");
                    }
                    System.out.println(responseJson);
                }else{
                    testCase.setResult("测试关闭");
                }
            }
        }
  }
}
(3)、输出测试结果到指定excel,但是每次输出的内容不覆盖,可利用当前时间精确到秒作为excel名称。

新增日期工具类:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
    public static String getCurrentDate(){
        Date date =new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-DD_hh_mm_ss");
        return  simpleDateFormat.format(date);
    }
}

在ApiTest类中,添加代码:

 String resultPath = System.getProperty("user.dir")+ File.separator+"data"+File.separator+"result_API_"+ DateUtil.getCurrentDate()+".xlsx";
        ExcelUtils.getInstance().exportObjects2Excel( list, TestCase.class, resultPath);
(4)、发送测试结果到指定邮箱。

在项目的resources文件夹下新增emailConfig.properties文件


image.png

新增ConfigurationUtil工具类,用于读取上述配置文件

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

     public class ConfigurationUtil {
        static  Configuration configuration;
        public static Configuration getCommonsPropertis() {
            try {
                configuration = new PropertiesConfiguration("emailConfig.properties");
            } catch (ConfigurationException e) {
                e.printStackTrace();
            }
            return configuration;
        }
}

新增EmailParams 类,获取properties文件中各参数

import com.sc.util.ConfigurationUtil;
import org.apache.commons.configuration.Configuration;

public class EmailParams {
   // public static String filePath ="./src/main/java/com/test/properties/emailConfig.properties";
    public static final Configuration file = ConfigurationUtil.getCommonsPropertis();
    public static final String host = file.getString("mail.host");
    public static final String username = file.getString("mail.username");
    public static final String password = file.getString("mail.password");
    public static final String title = file.getString("mail.title");
    public static final String[] tousers = file.getStringArray("mail.touser");
    public static final String[] ccaddress = file.getStringArray("mail.ccaddress");

}

创建EmailUtils工具类,用于发送邮件。

public class EmailUtils {

    public static  HtmlEmail emailSet(String title,String emailMsg,String fromEmail,String ps,String[] toEmail) throws EmailException {
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(EmailParams.host);
        email.setAuthentication(fromEmail,ps);
        email.setFrom(fromEmail);//发件人
        for(String touser:toEmail){
            email.addTo(touser);//收件人
        }

        email.setSubject(title); //邮件标题
        email.setHtmlMsg(emailMsg);//邮件内容
        return email;
    }
 //发送一个多个本地附件的邮件
    public static void  sendEmailWithAttachment(String title,String emailMsg,String fromEmail,String ps,String[] toEmail,String... filepath) throws EmailException {
        HtmlEmail email =emailSet(title,emailMsg,fromEmail,ps,toEmail);
         for(String s:filepath){
            EmailAttachment emailAttachment = new EmailAttachment();
            emailAttachment.setPath(s);
            emailAttachment.setDisposition(EmailAttachment.ATTACHMENT);
            emailAttachment.setDescription("测试结果");
            File f = new File(s);
            emailAttachment.setName(f.getName());
            email.attach(emailAttachment);
        }
        email.send();
    }
}

在ApiTest类中,执行邮件发送操作即可。

  EmailUtils.sendEmailWithAttachment("api测试结果","具体测试结果,请查看附件,谢谢!", EmailParams.username,EmailParams.password,EmailParams.tousers,resultPath);
上一篇下一篇

猜你喜欢

热点阅读