Java接口自动化测试框架系列(八)测试结果通知(钉钉通知)
通过前七步的框架搭建,此时框架已经可以开始进行接口测试了,但是运行的结果需要手动去项目的工作空间去查看,非常不方便。
很多公司使用的钉钉来进行日常办公的沟通,我们也可以通过发送钉钉消息,来推送测试结果。
钉钉设置
在钉钉群聊的智能群助手中选择添加自定义机器人
机器人添加完成后可以给机器人进行取名、获取webhook与密钥。
代码编写
新建DingTalkRobot方法类
package com.Auto_Test.utils; import java.net.URLEncoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.tomcat.util.codec.binary.Base64; public class DingTalkRobot { /** * 钉钉机器人签名 */ private String secret; /** * 钉钉机器人webhook */ private String url; public DingTalkRobot(String secret, String url) { this.secret = secret; this.url = url; } /* * 方法描述 获取签名 */ private String signature(String timestamp) throws Exception { String stringToSign = timestamp + "\n" + secret; Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8")); return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8"); } public String sendLinkMsg(String msg) throws Exception { String timestamp = String.valueOf(System.currentTimeMillis()); CloseableHttpClient httpclient = HttpClients.createDefault(); String postUrl = url + "×tamp=" + timestamp + "&sign=" + signature(timestamp); HttpPost httppost = new HttpPost(postUrl); httppost.addHeader("Content-Type", "application/json; charset=utf-8"); httppost.addHeader("sign", signature(timestamp)); httppost.addHeader("timestamp", timestamp); StringEntity se = new StringEntity(msg, "utf-8"); httppost.setEntity(se); String result = null; CloseableHttpResponse response = httpclient.execute(httppost); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { System.out.println("信息发送成功"); result = EntityUtils.toString(response.getEntity()); } return result; } }
新建监听类
package com.Auto_Test.listeners; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.naming.java.javaURLContextFactory; import org.testng.IReporter; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.xml.XmlSuite; import com.Auto_Test.utils.DingTalkRobot; import com.alibaba.fastjson.JSONObject; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; import com.aventstack.extentreports.model.TestAttribute; public class DingTalkListener implements IReporter { //总体测试数量 int totalTestCase = 0; //成功率 double passRate = 0; //失败数量 int failNum = 0; //成功数量 int passNum = 0; //跳过数量 int skipNum = 0; //测试名称 String projectName=""; @Override public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) { for (ISuite suite : suites) { Map<String, ISuiteResult> results = suite.getResults(); projectName += results.keySet(); //获取总数据 for (ISuiteResult suiteResult : results.values()) { //获取各状态用例的数量 passNum += suiteResult.getTestContext().getPassedTests().getAllResults().size(); failNum += suiteResult.getTestContext().getFailedTests().getAllResults().size(); skipNum += suiteResult.getTestContext().getSkippedTests().getAllResults().size(); } } //获取用例总数 totalTestCase = passNum + failNum + skipNum; //获取用例成功率 passRate = new BigDecimal((float) passNum / totalTestCase * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); //机器人的webhook地址 String url = "***"; //机器人密钥 String secret = "***"; // 调用钉钉工具类的发消息方法 DingTalkRobot dingTalkRobot = new DingTalkRobot(secret, url); try { //调用发送方法 dingTalkRobot.sendLinkMsg(convertToCard()); } catch (Exception e) { e.printStackTrace(); } } /** * 测试组装发送的消息 */ private String convertToCard() { JSONObject sendObj = new JSONObject(); JSONObject actionCardObj = new JSONObject(); //获取系统时间并进行格式化 Date day = new Date(); SimpleDateFormat days = new SimpleDateFormat("yyyy-MM-dd"); actionCardObj.put("title", "上海SAAS电子保函接口测试"); // \n换行 \t空格 actionCardObj.put( "text", "![screenshot](http://58.**.218.***:***/job/%E7%94%B5%E5%AD%90%E4%BF%9D%E5%87%BD%E6%8E%A5%E5%8F%A3%E8%87%AA%E5%8A%A8%E5%8C%96/ws/src/Log/AutoLog.png) " + "\n\n执行接口:"+projectName+ "\n\n用例总数:" + totalTestCase + "\t通过率:" + passRate + "\n\n通过:" + passNum + "\t失败:" + failNum + "\t跳过:" + skipNum ); //示例:dingtalk://dingtalkclient/page/link?url=http%3A%2F%2Fwww.dingtalk.com&pc_slide=false //dingtalk://dingtalkclient/page/link?url= //&pc_slide为false时则为外部打开 actionCardObj.put("singleURL", "dingtalk://dingtalkclient/page/link?url=http://58.**.218.***:***/job/%E7%94%B5%E5%AD%90%E4%BF%9D%E5%87%BD%E6%8E%A5%E5%8F%A3%E8%87%AA%E5%8A%A8%E5%8C%96/ws/TestRport/"+days.format(day)+"/SaaSReport.html&pc_slide=false"); actionCardObj.put("singleTitle", "详细报告"); sendObj.put("msgtype", "actionCard"); sendObj.put("actionCard", actionCardObj); return sendObj.toString(); } }
在TestNG.xml中添加DingTalkListener方法的监听,运行完成后会在钉钉群里发送信息通知,点击详细报告自动跳转到ExtentReports测试报告上(图片与测试报告的跳转路径需要进行配置)
<!-- 注册监听 --> <listeners> <listener class-name="com.Auto_Test.listeners.DingTalkListener"/> </listeners>
需要此项目的可以加我微信15224918643获取,也可以一起交流技术。
欢迎打扰