ExtentReports测试报告优化改进笔记(二)

1、pom引入jar包:

 <dependency>
        <groupId>com.aventstack</groupId>
        <artifactId>extentreports</artifactId>
        <version>3.1.5</version>
    </dependency>
    <dependency>
        <groupId>com.vimalselvam</groupId>
        <artifactId>testng-extentsreport</artifactId>
        <version>1.3.1</version>
    </dependency>

2、封装监听器
1)、创建一个MyExtentTestNgFormatter的类,代码如下:

package listener;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.ResourceCDN;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.vimalselvam.testng.EmailReporter;
import com.vimalselvam.testng.NodeName;
import com.vimalselvam.testng.SystemInfo;
import com.vimalselvam.testng.listener.ExtentTestNgFormatter;
import org.testng.*;
import org.testng.xml.XmlSuite;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyExtentTestNgFormatter extends ExtentTestNgFormatter{
    private static final String REPORTER_ATTR = "extentTestNgReporter";
    private static final String SUITE_ATTR = "extentTestNgSuite";
    private ExtentReports reporter;
    private List<String> testRunnerOutput;
    private Map<String, String> systemInfo;
    private ExtentHtmlReporter htmlReporter;

    private static ExtentTestNgFormatter instance;

    public MyExtentTestNgFormatter() {
        setInstance(this);
        testRunnerOutput = new ArrayList<>();
        // reportPath 报告路径
        String reportPathStr = System.getProperty("reportPath");
        File reportPath;

        try {
            reportPath = new File(reportPathStr);
        } catch (NullPointerException e) {
            reportPath = new File(TestNG.DEFAULT_OUTPUTDIR);
        }

        if (!reportPath.exists()) {
            if (!reportPath.mkdirs()) {
                throw new RuntimeException("Failed to create output run directory");
            }
        }
        //  报告名report.html
        File reportFile = new File(reportPath, "report.html");
        // 邮件报告名emailable-report.html
        File emailReportFile = new File(reportPath, "emailable-report.html");

        htmlReporter = new ExtentHtmlReporter(reportFile);
        EmailReporter emailReporter = new EmailReporter(emailReportFile);
        reporter = new ExtentReports();
        //  如果cdn.rawgit.com访问不了,可以设置为:ResourceCDN.EXTENTREPORTS或者ResourceCDN.GITHUB
        htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);
        reporter.attachReporter(htmlReporter, emailReporter);
    }

    /**
     * Gets the instance of the {@link ExtentTestNgFormatter}
     *
     * @return The instance of the {@link ExtentTestNgFormatter}
     */
    public static ExtentTestNgFormatter getInstance() {
        return instance;
    }

    private static void setInstance(ExtentTestNgFormatter formatter) {
        instance = formatter;
    }

    /**
     * Gets the system information map
     *
     * @return The system information map
     */
    public Map<String, String> getSystemInfo() {
        return systemInfo;
    }

    /**
     * Sets the system information
     *
     * @param systemInfo The system information map
     */
    public void setSystemInfo(Map<String, String> systemInfo) {
        this.systemInfo = systemInfo;
    }

    public void onStart(ISuite iSuite) {
        if (iSuite.getXmlSuite().getTests().size() > 0) {
            ExtentTest suite = reporter.createTest(iSuite.getName());
            String configFile = iSuite.getParameter("report.config");

            if (!Strings.isNullOrEmpty(configFile)) {
                htmlReporter.loadXMLConfig(configFile);
            }

            String systemInfoCustomImplName = iSuite.getParameter("system.info");
            if (!Strings.isNullOrEmpty(systemInfoCustomImplName)) {
                generateSystemInfo(systemInfoCustomImplName);
            }

            iSuite.setAttribute(REPORTER_ATTR, reporter);
            iSuite.setAttribute(SUITE_ATTR, suite);
        }
    }

    private void generateSystemInfo(String systemInfoCustomImplName) {
        try {
            Class<?> systemInfoCustomImplClazz = Class.forName(systemInfoCustomImplName);
            if (!SystemInfo.class.isAssignableFrom(systemInfoCustomImplClazz)) {
                throw new IllegalArgumentException("The given system.info class name <" + systemInfoCustomImplName +
                        "> should implement the interface <" + SystemInfo.class.getName() + ">");
            }

//            SystemInfo t = (SystemInfo) systemInfoCustomImplClazz.newInstance();
            SystemInfo t1 = (SystemInfo) systemInfoCustomImplClazz.getDeclaredConstructor().newInstance();
            setSystemInfo(t1.getSystemInfo());
            systemInfoCustomImplClazz.getDeclaredConstructors();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            throw new IllegalStateException(e);
        }
    }

    public void onFinish(ISuite iSuite) {
    }


    public void onTestStart(ITestResult iTestResult) {
        MyReporter.setTestName(iTestResult.getName());
    }

    public void onTestSuccess(ITestResult iTestResult) {

    }

    public void onTestFailure(ITestResult iTestResult) {

    }

    public void onTestSkipped(ITestResult iTestResult) {

    }

    public void onTestFailedButWithinSuccessPercentage(ITestResult iTestResult) {

    }

    public void onStart(ITestContext iTestContext) {
        ISuite iSuite = iTestContext.getSuite();
        ExtentTest suite = (ExtentTest) iSuite.getAttribute(SUITE_ATTR);
        ExtentTest testContext = suite.createNode(iTestContext.getName());
        // 自定义报告
        // 将MyReporter.report 静态引用赋值为 testContext。
        // testContext 是 @Test每个测试用例时需要的。report.log可以跟随具体的测试用例。另请查阅源码。
        MyReporter.report = testContext;
        iTestContext.setAttribute("testContext", testContext);
    }

    public void onFinish(ITestContext iTestContext) {
        ExtentTest testContext = (ExtentTest) iTestContext.getAttribute("testContext");
        if (iTestContext.getFailedTests().size() > 0) {
            testContext.fail("Failed");
        } else if (iTestContext.getSkippedTests().size() > 0) {
            testContext.skip("Skipped");
        } else {
            testContext.pass("Passed");
        }
    }

    public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
        if (iInvokedMethod.isTestMethod()) {
            ITestContext iTestContext = iTestResult.getTestContext();
            ExtentTest testContext = (ExtentTest) iTestContext.getAttribute("testContext");
            ExtentTest test = testContext.createNode(iTestResult.getName(), iInvokedMethod.getTestMethod().getDescription());
            iTestResult.setAttribute("test", test);
        }
    }

    public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
        if (iInvokedMethod.isTestMethod()) {
            ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
            List<String> logs = Reporter.getOutput(iTestResult);
            for (String log : logs) {
                test.info(log);
            }

            int status = iTestResult.getStatus();
            if (ITestResult.SUCCESS == status) {
                test.pass("Passed");
            } else if (ITestResult.FAILURE == status) {
                test.fail(iTestResult.getThrowable());
            } else {
                test.skip("Skipped");
            }

            for (String group : iInvokedMethod.getTestMethod().getGroups()) {
                test.assignCategory(group);
            }
        }
    }

    /**
     *向报表中添加屏幕快照图像文件。此方法只能在配置方法中使用
     * and the {@link ITestResult} is the mandatory parameter
     *
     * @param iTestResult The {@link ITestResult} object
     * @param filePath    The image file path
     * @throws IOException {@link IOException}
     */
    public void addScreenCaptureFromPath(ITestResult iTestResult, String filePath) throws IOException {
        ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
        test.addScreenCaptureFromPath(filePath);
    }

    public void addScreenCaptureFromPath(String filePath) throws IOException {
        ITestResult iTestResult = Reporter.getCurrentTestResult();
        Preconditions.checkState(iTestResult != null);
        ExtentTest test = (ExtentTest) iTestResult.getAttribute("test");
        test.addScreenCaptureFromPath(filePath);
    }

    /**
     * 设置测试运行程序输出
     *
     * @param message The message to be logged
     */
    public void setTestRunnerOutput(String message) {
        testRunnerOutput.add(message);
    }

    public void generateReport(List<XmlSuite> list, List<ISuite> list1, String s) {
        if (getSystemInfo() != null) {
            for (Map.Entry<String, String> entry : getSystemInfo().entrySet()) {
                reporter.setSystemInfo(entry.getKey(), entry.getValue());
            }
        }
        reporter.setTestRunnerOutput(testRunnerOutput);
        reporter.flush();
    }

    /**
     *将新节点添加到测试中。应该已经使用{@link NodeName}设置了节点名
     */
    public void addNewNodeToTest() {
        addNewNodeToTest(NodeName.getNodeName());
    }

    /**
     * 使用给定的节点名将新节点添加到测试中
     *
     * @param nodeName The name of the node to be created
     */
    public void addNewNodeToTest(String nodeName) {
        addNewNode("test", nodeName);
    }

    /**
     * 向套件中添加新节点。应该已经使用{@link NodeName}设置了节点名
     */
    public void addNewNodeToSuite() {
        addNewNodeToSuite(NodeName.getNodeName());
    }

    /**
     *将具有给定节点名的新节点添加到套件中
     *
     * @param nodeName The name of the node to be created
     */
    public void addNewNodeToSuite(String nodeName) {
        addNewNode(SUITE_ATTR, nodeName);
    }

    private void addNewNode(String parent, String nodeName) {
        ITestResult result = Reporter.getCurrentTestResult();
        Preconditions.checkState(result != null);
        ExtentTest parentNode = (ExtentTest) result.getAttribute(parent);
        ExtentTest childNode = parentNode.createNode(nodeName);
        result.setAttribute(nodeName, childNode);
    }

    /**
     * 向节点添加信息日志消息。应该已经使用{@link NodeName}设置了节点名
     *
     * @param logMessage The log message string
     */
    public void addInfoLogToNode(String logMessage) {
        addInfoLogToNode(logMessage, NodeName.getNodeName());
    }

    /**
     * Adds a info log message to the node
     *
     * @param logMessage The log message string
     * @param nodeName   The name of the node
     */
    public void addInfoLogToNode(String logMessage, String nodeName) {
        ITestResult result = Reporter.getCurrentTestResult();
        Preconditions.checkState(result != null);
        ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
        test.info(logMessage);
    }

    /**
     * Marks the node as failed. The node name should have been set already using {@link NodeName}
     *
     * @param t The {@link Throwable} object
     */
    public void failTheNode(Throwable t) {
        failTheNode(NodeName.getNodeName(), t);
    }

    /**
     * Marks the given node as failed
     *
     * @param nodeName The name of the node
     * @param t        The {@link Throwable} object
     */
    public void failTheNode(String nodeName, Throwable t) {
        ITestResult result = Reporter.getCurrentTestResult();
        Preconditions.checkState(result != null);
        ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
        test.fail(t);
    }

    /**
     * Marks the node as failed. The node name should have been set already using {@link NodeName}
     *
     * @param logMessage The message to be logged
     */
    public void failTheNode(String logMessage) {
        failTheNode(NodeName.getNodeName(), logMessage);
    }

    /**
     * Marks the given node as failed
     *
     * @param nodeName   The name of the node
     * @param logMessage The message to be logged
     */
    public void failTheNode(String nodeName, String logMessage) {
        ITestResult result = Reporter.getCurrentTestResult();
        Preconditions.checkState(result != null);
        ExtentTest test = (ExtentTest) result.getAttribute(nodeName);
        test.fail(logMessage);
    }


}

2)、创建类:MyReporter,set和get方法

package listener;

import com.aventstack.extentreports.ExtentTest;

public class MyReporter {
    public static ExtentTest report;
    private static String testName;

    public static String getTestName() {
        return testName;
    }

    public static void setTestName(String testName) {
        MyReporter.testName = testName;
    }

}

3)、在config包下创建类:MySystemInfo,实现接口:SystemInfo,可配置测试人员,测试环境等数据

package config;

import com.vimalselvam.testng.SystemInfo;

import java.util.HashMap;
import java.util.Map;

public class MySystemInfo implements SystemInfo {

    @Override
    public Map<String, String> getSystemInfo() {
        Map<String,String> systemInfo = new HashMap<>();
        systemInfo.put("测试人员","whm");
        return systemInfo;
    }
}

4)、在resource》report下设置extent-config.xml
(路径:src/main/resources/report/extent-config.xml),可配置报告显示内容(如标题、年月日格式等),内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<extentreports>
    <configuration>
        <timeStampFormat>yyyy-MM-dd HH:mm:ss</timeStampFormat>
        <!-- report theme -->
        <!-- standard, dark -->
        <theme>dark</theme>

        <!-- document encoding -->
        <!-- defaults to UTF-8 -->
        <encoding>UTF-8</encoding>

        <!-- protocol for script and stylesheets -->
        <!-- defaults to https -->
        <protocol>https</protocol>

        <!-- title of the document -->
        <documentTitle>apis自动化测试报告</documentTitle>

        <!-- report name - displayed at top-nav -->
        <reportName>apis自动化测试报告</reportName>

        <!-- report headline - displayed at top-nav, after reportHeadline -->
        <reportHeadline>Dmallmax自动化测试报告</reportHeadline>

        <!-- global date format override -->
        <!-- defaults to yyyy-MM-dd -->
        <dateFormat>yyyy-MM-dd</dateFormat>

        <!-- global time format override -->
        <!-- defaults to HH:mm:ss -->
        <timeFormat>HH:mm:ss</timeFormat>

        <!-- custom javascript -->
        <scripts>
            <![CDATA[
        $(document).ready(function() {

        });
      ]]>
        </scripts>

        <!-- custom styles -->
        <styles>
            <![CDATA[

      ]]>
        </styles>
    </configuration>
</extentreports>

5)、testng.xml中设置如下:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="SAAS项目">
    <parameter name="report.config" value="src/main/resources/report/extent-config.xml"/>
    <parameter name="system.info" value="config.MySystemInfo"/>

    <test name="Mis系统">
        <classes>
            <class name="testcase.VenderTest"/>
            <class name="testcase.CaigouTest"/>
        </classes>
    </test>
    <test name="H5商城">
        <classes>
            <class name="testScript.MarketUserOrder"/>
        </classes>
    </test>

    <listeners>
        <listener class-name="listener.MyExtentTestNgFormatter"/>
        <!--失败重试-->
        <!--        <listener class-name="listener.testngListener.FailedRetryListener"/>-->
        <!--        <listener class-name="listener.testngListener.TestngListener"/>-->
    </listeners>
</suite>

3、整体项目目录如下:


4、运行结束,会在target-out目录下生成2个测试报告,报告名分别为:emailable-report.html、report.html;生成测试报告如图:


emailable-report.html

report.html

report.html
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,864评论 6 494
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,175评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,401评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,170评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,276评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,364评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,401评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,179评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,604评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,902评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,070评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,751评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,380评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,077评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,312评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,924评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,957评论 2 351