1.utils目錄下新建DingDingUtil類
package utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import restclient.RestClient;
import java.text.NumberFormat;
import java.util.HashMap;
/**
*釘釘機器人工具類
*/
public class DingDingUtil {
//通過釘釘機器人發送消息到釘釘群中
public static void sendVal(String url,String context)throws Exception{
HashMap<String,String> headermap = new HashMap<>();
headermap.put("Content-Type","application/json");
String entityString ="{'msgtype': 'text', 'text': {'content': '"+context+"'}}";
RestClient restClient = new RestClient();
CloseableHttpResponse closeableHttpResponse = restClient.post(url,entityString,headermap);
JSONObject responseJson = restClient.getResponseJson(closeableHttpResponse);
}
//folat數字轉換為百分號格式
public static String folatToPer(float folatNum){
NumberFormat numberFormat = NumberFormat.getPercentInstance();
String per=null;
try {
numberFormat.setMaximumFractionDigits(2); //精確到2位
per = numberFormat.format(folatNum);
ReportUtil.log("小數點數字轉百分數字符串:" + folatNum + " 轉為 " + per);
} catch (Exception e) {
e.printStackTrace();
}
return per;
}
public static void main(String[] args) {
String c=DingDingUtil.folatToPer((float) 5/7);
System.out.println(c);
}
}
RestClient類引用請參考下面這篇文章
https://blog.csdn.net/weixin_42884654/article/details/94634905
2.utils目錄下新建ReportUtil類,增加日志記錄
package utils;
import org.testng.Reporter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
*測試報告日志輸出工具類
*/
public class ReportUtil {
private static String splitTimeAndMsg = "---";
public static void log(String msg) {
long timeMillis = Calendar.getInstance().getTimeInMillis();
//TODO 日志記錄
// LoggerUtil.infoData(msg);
//獲取當前系統時間
long currentTime = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH時mm分ss秒");
Date date = new Date(currentTime);
System.out.println(formatter.format(date));
Reporter.log(formatter.format(date) + splitTimeAndMsg + msg, true);
}
}
3.釘釘上添加釘釘機器人,保存webhook
4.config目錄下ExtentTestNGIReporterListener類,增加釘釘機器人配置
package config;
import com.aventstack.extentreports.reporter.configuration.Theme;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.File;
import java.util.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.ResourceCDN;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.model.TestAttribute;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import utils.DingDingUtil;
import utils.ReportUtil;
/**
* 測試報告模板.
*/
public class ExtentTestNGIReporterListener implements IReporter {
//生成的路徑以及文件名
private static final String OUTPUT_FOLDER = "test-output/";
private static final String FILE_NAME = "index.html";
private ExtentReports extent;
@Override
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
init();
//統計suite下的成功、失敗、跳過和總的用例數
int suiteSize=0;
int suiteFailSize=0;
int suitePassSize=0;
int suiteSkipSize=0;
boolean createSuiteNode = false;
if(suites.size()>1){
createSuiteNode=true;
}
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
//如果suite里面沒有任何用例,直接跳過,不在報告里生成
if(result.size()==0){
continue;
}
ExtentTest suiteTest=null;
//存在多個suite的情況下,在報告中將同一個一個suite的測試結果歸為一類,創建一級節點。
if(createSuiteNode){
suiteTest = extent.createTest(suite.getName()).assignCategory(suite.getName());
}
boolean createSuiteResultNode = false;
if(result.size()>=1){
createSuiteResultNode=true;
}
for (ISuiteResult r : result.values()) {
ExtentTest resultNode;
ITestContext context = r.getTestContext();
if(createSuiteResultNode){
//沒有創建suite的情況下,將在SuiteResult的創建為一級節點,否則創建為suite的一個子節點。
if( null == suiteTest){
resultNode = extent.createTest(r.getTestContext().getName());
}else{
resultNode = suiteTest.createNode(r.getTestContext().getName());
}
}else{
resultNode = suiteTest;
}
if(resultNode != null){
resultNode.getModel().setName(suite.getName()+" : "+r.getTestContext().getName());
if(resultNode.getModel().hasCategory()){
resultNode.assignCategory(r.getTestContext().getName());
}else{
resultNode.assignCategory(suite.getName(),r.getTestContext().getName());
}
resultNode.getModel().setStartTime(r.getTestContext().getStartDate());
resultNode.getModel().setEndTime(r.getTestContext().getEndDate());
//統計SuiteResult下的數據
int passSize = r.getTestContext().getPassedTests().size();
int failSize = r.getTestContext().getFailedTests().size();
int skipSize = r.getTestContext().getSkippedTests().size();
suitePassSize += passSize;
suiteFailSize += failSize;
suiteSkipSize += skipSize;
if(failSize>0){
resultNode.getModel().setStatus(Status.FAIL);
}
resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",passSize,failSize,skipSize));
}
buildTestNodes(resultNode,context.getFailedTests(), Status.FAIL);
buildTestNodes(resultNode,context.getSkippedTests(), Status.SKIP);
buildTestNodes(resultNode,context.getPassedTests(), Status.PASS);
}
if(suiteTest!= null){
suiteTest.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",suitePassSize,suiteFailSize,suiteSkipSize));
if(suiteFailSize>0){
suiteTest.getModel().setStatus(Status.FAIL);
}
}
}
// for (String s : Reporter.getOutput()) {
// extent.setTestRunnerOutput(s);
// }
extent.flush();
suiteSize = suiteFailSize + suitePassSize + suiteSkipSize;
//新加釘釘機器人測試報告
String pass= DingDingUtil.folatToPer((float)suitePassSize/suiteSize);
String url ="https://oapi.dingtalk.com/robot/send?access_token=457d8eb62b4f0b1e5781f3862c0b9e77ab21f";
String context="此次運行接口用例,總用例數為:"+suiteSize+";通過:"+suitePassSize+";失敗:"+suiteFailSize+";跳過:"+suiteSkipSize+";通過率為:"+pass;
try {
DingDingUtil.sendVal(url,context);
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
//文件夾不存在的話進行創建
File reportDir= new File(OUTPUT_FOLDER);
if(!reportDir.exists()&& !reportDir .isDirectory()){
reportDir.mkdir();
}
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
htmlReporter.config().setDocumentTitle("秀場-接口自動化測試報告");
htmlReporter.config().setReportName("秀場-接口自動化測試報告");
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
//設置報告背景顏色
htmlReporter.config().setTheme(Theme.DARK);
htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);
htmlReporter.config().setCSS(".node.level-1 ul{ display:none;} .node.level-1.active ul{display:block;}");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setReportUsesManualConfiguration(true);
// 設置系統信息
Properties properties = System.getProperties();
// extent.setSystemInfo("os.name",properties.getProperty("os.name","未知"));
// extent.setSystemInfo("os.arch",properties.getProperty("os.arch","未知"));
// extent.setSystemInfo("os.version",properties.getProperty("os.version","未知"));
// extent.setSystemInfo("java.version",properties.getProperty("java.version","未知"));
// extent.setSystemInfo("java.home",properties.getProperty("java.home","未知"));
// extent.setSystemInfo("user.name",properties.getProperty("user.name","未知"));
// extent.setSystemInfo("user.dir",properties.getProperty("user.dir","未知"));
// 設置自定義配置信息
Map<String,String> systemmap = new HashMap<>();
MySystemInfo mySystemInfo = new MySystemInfo();
systemmap = mySystemInfo.getSystemInfo();
for (Map.Entry<String,String> entry:
systemmap.entrySet()) {
extent.setSystemInfo(entry.getKey(),entry.getValue());
}
}
private void buildTestNodes(ExtentTest extenttest, IResultMap tests, Status status) {
//存在父節點時,獲取父節點的標簽
String[] categories=new String[0];
if(extenttest != null ){
List<TestAttribute> categoryList = extenttest.getModel().getCategoryContext().getAll();
categories = new String[categoryList.size()];
for(int index=0;index<categoryList.size();index++){
categories[index] = categoryList.get(index).getName();
}
}
ExtentTest test;
if (tests.size() > 0) {
//調整用例排序,按時間排序
Set<ITestResult> treeSet = new TreeSet<ITestResult>(new Comparator<ITestResult>() {
@Override
public int compare(ITestResult o1, ITestResult o2) {
return o1.getStartMillis()<o2.getStartMillis()?-1:1;
}
});
treeSet.addAll(tests.getAllResults());
for (ITestResult result : treeSet) {
Object[] parameters = result.getParameters();
String name="";
//如果有參數,則使用參數的toString組合代替報告中的name
for(Object param:parameters){
name+=param.toString();
}
if(name.length()>0){
if(name.length()>50){
name= name.substring(0,49)+"...";
}
}else{
name = result.getMethod().getMethodName();
}
if(extenttest==null){
test = extent.createTest(name);
}else{
//作為子節點進行創建時,設置同父節點的標簽一致,便於報告檢索。
test = extenttest.createNode(name).assignCategory(categories);
}
//test.getModel().setDescription(description.toString());
//test = extent.createTest(result.getMethod().getMethodName());
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
List<String> outputList = Reporter.getOutput(result);
for(String output:outputList){
//將用例的log輸出報告中
// test.debug(output);
test.debug(output.replaceAll("<","<").replaceAll(">",">"));
}
if (result.getThrowable() != null) {
test.log(status, result.getThrowable());
}
else {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
}
test.getModel().setStartTime(getTime(result.getStartMillis()));
test.getModel().setEndTime(getTime(result.getEndMillis()));
}
}
}
private Date getTime(long millis) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
}
增加部分如下圖:
5.使用testng里的xml文件執行test,釘釘機器人發送測試結果
轉自: https://blog.csdn.net/weixin_42884654/article/details/103076146