范围报告仅显示testng maven selenium Java框架的最后运行结果

问题描述

我正在使用testng 6.9.10,extentreports 3.1.5。使用maven surefire插件以及forkfork和复用forks可以并行运行测试。 (即chrome浏览器打开的两个实例,其中两个测试类在我设置forkcount-> 2和reuseforks-> true时并行运行)

mvn test -Dgroups=group1 

(有两个属于class1的测试类)。问题在于扩展区报告仅显示上次运行的结果。

我在pom.xml中仅包含了侦听器类(在其他任何地方都没有,作为BaseTest类的一部分不在@beforeclass或@afterclass中)

  <property>
    <name>listener</name>
    <value>util.listener.TestExtentListener</value>
  </property>


   <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.0</version>
    <forkCount>2</forkCount>
    <reuseForks>true</reuseForks>

请问有什么解决方法吗?

public class ExtentManager {

private static ExtentReports extent;
private static String reportFileName = "Test-Automaton-Report"+".html";
private static String fileSeperator = System.getProperty("file.separator");
private static String reportFilepath = System.getProperty("user.dir") +fileSeperator+ "TestReport";
private static String reportFileLocation =  reportFilepath +fileSeperator+ reportFileName;


public static ExtentReports getInstance() {
    if (extent == null)
        createInstance();
    return extent;
}

//Create an extent report instance
public static ExtentReports createInstance() {
    String fileName = getReportPath(reportFilepath);

    ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName);
    htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
    htmlReporter.config().setChartVisibilityOnOpen(true);
    htmlReporter.config().setTheme(Theme.STANDARD);
    htmlReporter.config().setDocumentTitle(reportFileName);
    htmlReporter.config().setEncoding("utf-8");
    htmlReporter.config().setReportName(reportFileName);
    htmlReporter.config().setTimeStampFormat("EEEE,MMMM dd,yyyy,hh:mm a '('zzz')'");

    extent = new ExtentReports();

    extent.attachReporter(htmlReporter);
    //Set environment details
    extent.setSystemInfo("OS","Mac");
    extent.setSystemInfo("AUT","QA");

    return extent;
 }

//Create the report path
private static String getReportPath (String path) {
    File testDirectory = new File(path);
    if (!testDirectory.exists()) {
        if (testDirectory.mkdir()) {
            System.out.println("Directory: " + path + " is created!" );
            return reportFileLocation;
        } else {
            System.out.println("Failed to create directory: " + path);
            return System.getProperty("user.dir");
        }
    } else {
        System.out.println("Directory already exists: " + path);
    }
    return reportFileLocation;
}

}

public class ExtentTestManager {
static Map<Integer,ExtentTest> extentTestMap = new HashMap<Integer,ExtentTest>();
static ExtentReports extent = ExtentManager.getInstance();

public static synchronized ExtentTest getTest() {
    return (ExtentTest) extentTestMap.get((int) (long) (Thread.currentThread().getId()));
}

public static synchronized void endTest() {
    extent.flush();
}

public static synchronized ExtentTest startTest(String testName) {
    ExtentTest test = extent.createTest(testName);
    extentTestMap.put((int) (long) (Thread.currentThread().getId()),test);
    return test;
}
}

public class TestExtentListener implements ITestListener {

ExtentTest test;
private static ThreadLocal<ExtentTest> extentTestThreadLocal = new ThreadLocal<ExtentTest>();


public void onStart(ITestContext context) {
    System.out.println("*** Test Suite " + context.getName() + " started ***");
}

public void onFinish(ITestContext context) {
    System.out.println(("*** Test Suite " + context.getName() + " ending ***"));
    ExtentTestManager.endTest();
    ExtentManager.getInstance().flush();
}

public void onTestStart(ITestResult result) {
    System.out.println(("*** Running test method " + result.getMethod().getMethodName() + "..."));
    test = ExtentTestManager.startTest(result.getMethod().getMethodName());
    extentTestThreadLocal.set(test);
}

public void onTestSuccess(ITestResult result) {
    System.out.println("*** Executed " + result.getMethod().getMethodName() + " test successfully...");
    extentTestThreadLocal.get().log(Status.PASS,"Test passed");
}

public void onTestFailure(ITestResult result) {
    System.out.println("*** Test execution " + result.getMethod().getMethodName() + " failed...");
    extentTestThreadLocal.get().log(Status.FAIL,"Test Failed");
}

public void onTestSkipped(ITestResult result) {
    System.out.println("*** Test " + result.getMethod().getMethodName() + " skipped...");
    extentTestThreadLocal.get().log(Status.SKIP,"Test Skipped");
}

public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
    System.out.println("*** Test failed but within percentage % " + result.getMethod().getMethodName());
}

}

解决方法

您可能没有在Java中使用线程本地类来使扩展报告线程安全。否则,对象将被覆盖,范围报告仅显示活动的测试结果。

您可以执行以下操作:

ExtentReports extent = ExtentReportGenerator.ExtentReport();
    ExtentTest test;;

    private static ThreadLocal<ExtentTest> extent_test = new ThreadLocal<ExtentTest>();

有关更多详细信息,您可以参考此博客。

https://www.automationinja.com/post/thread-safe-extent-report-in-selenium

,
    If you use xml file to your testclasses all report will appear in extent report 
    
    This is my XML 
    
        <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
    <suite name="TC_WorldAirFares Automation Test Suite">
    
        <listeners>
            <listener class-name="ExtentReports.ExtentReporterNG" />
        </listeners>
  <suite name="Suite" parallel="instances" thread-count="2">
    <test name="TC Automation Test Suite">
            <classes>
    
                <class name="Footerlinks" />
                <class name="HeaderLinks" />
                <class name="BookYourFlightsNow" />
              
            </classes>
        </test>
    
       
    </suite>
    
    
    keep class for extentreports
    
    here extent report class (XML file listen your extentreport class and generate reports for you test classes
    
        package ExtentReports;
    
    import com.relevantcodes.extentreports.ExtentReports;
    import com.relevantcodes.extentreports.ExtentTest;
    import com.relevantcodes.extentreports.LogStatus;
    import org.testng.*;
    import org.testng.xml.XmlSuite;
    
    import java.io.File;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    public class ExtentReporterNG implements IReporter {
        private ExtentReports extent;
    
        public void generateReport(List<XmlSuite> xmlSuites,List<ISuite> suites,String outputDirectory) {
            extent = new ExtentReports(outputDirectory + File.separator
                    + "Extent.html",true);
    
            for (ISuite suite : suites) {
                Map<String,ISuiteResult> result = suite.getResults();
    
                for (ISuiteResult r : result.values()) {
                    ITestContext context = r.getTestContext();
    
                    buildTestNodes(context.getPassedTests(),LogStatus.PASS);
                    buildTestNodes(context.getFailedTests(),LogStatus.FAIL);
                    buildTestNodes(context.getSkippedTests(),LogStatus.SKIP);
                }
            }
    
            extent.flush();
            extent.close();
        }
    
        private void buildTestNodes(IResultMap tests,LogStatus status) {
            ExtentTest test;
    
            if (tests.size() > 0) {
                for (ITestResult result : tests.getAllResults()) {
                    test = extent.startTest(result.getMethod().getMethodName());
    
                    test.setStartedTime(getTime(result.getStartMillis()));
                    test.setEndedTime(getTime(result.getEndMillis()));
    
                    for (String group : result.getMethod().getGroups())
                        test.assignCategory(group);
    
                    if (result.getThrowable() != null) {
                        test.log(status,result.getThrowable());
                    } else {
                        test.log(status,"Test " + status.toString().toLowerCase()
                                + "ed");
                    }
    
                    extent.endTest(test);
                }
            }
        }
    
        private Date getTime(long millis) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(millis);
            return calendar.getTime();
        }
    }

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...