Sagar Jani
Sagar Jani

Reputation: 161

ExtentReports: detachReporter() method

I am using a suite file with multiple suites inside the testng.xml file as follows:

<suite-files>
        <suite-file path="suite1"></suite-file>
        <suite-file path="suite2"></suite-file>
</suite-files>

I am initializing ExtentReport in BeforeSuite.

private static void initializeExtentReport(Configuration config) {
        if (extent == null) {
            extent = new ExtentReports();
            htmlReporter = new ExtentHtmlReporter("reportLocation");
            ClassLoader classLoader = ExtentReportService.class.getClassLoader();
            File extentConfigFile = new File(classLoader.getResource("extent-config.xml").getFile());
            htmlReporter.loadXMLConfig(extentConfigFile);
            extent.attachReporter(htmlReporter);
            extent.setSystemInfo("Environment", config.getAutomationServer());
        }
    }

In AfterSuite, I am calling flush().

So basically the issue is, when the before suite is called for the second suite, The check (extent==null), is coming false. I also went through the JavaDocs for ExtentReports and I found a method detachReporter() there. But I am not able to access by my IDE. Tried many variations but to no fruition.

EDIT:

Right now what really happens is, I am using custom names for reports, so that no two report names are the same. And, when I was using with the same name, the results would be over written in the same file for the suites.

Upvotes: 0

Views: 427

Answers (1)

foursyth
foursyth

Reputation: 527

A better approach here is to use a singleton like so:

public class Extent 
    implements Serializable {

    private static final long serialVersionUID = 1L;

    private static class ExtentReportsLoader {

        private static final ExtentReports INSTANCE = new ExtentReports();

        static {
        }
    }

    public static synchronized ExtentReports getInstance() {
        return ExtentReportsLoader.INSTANCE;
    }

    @SuppressWarnings("unused")
    private ExtentReports readResolve() {
        return ExtentReportsLoader.INSTANCE;
    }

}

Usage:

ExtentReports extent = Extent.getInstance();

So your code becomes:

private static void initializeExtentReport(Configuration config) {
    extent = Extent.getInstance();
    if (extent.getStartedReporters().isEmpty()) {
        htmlReporter = new ExtentHtmlReporter("reportLocation");
        ClassLoader classLoader = ExtentReportService.class.getClassLoader();
        File extentConfigFile = new File(classLoader.getResource("extent-config.xml").getFile());
        htmlReporter.loadXMLConfig(extentConfigFile);
        extent.attachReporter(htmlReporter);
        extent.setSystemInfo("Environment", config.getAutomationServer());
    }
}

I would further recommend getting rid of all shared variables for extent/htmlReporter and directly use the Singleton

Upvotes: 1

Related Questions