How do Extent Reports generate an HTML report when the test gives error outside the @Test tag?

I created a report template for my test project that is so far meeting my demand, however, if the test fails outside the '@Test ' tag the report is not generated (being some connection error, or driver error, etc). I believe this happens because the test doesn't pass the @AfterMethod and @AfterTest tags when errors of this kind happen, and therefore I can't run the extent commands.flush () and extent.close () and the html file is not created. Something suggestion of what can I do? Following code in Java below:

@BeforeTest
public void startTest() {

    className = this.getClass().getName();
    String dateName = new SimpleDateFormat("dd-MM-yyyy hhmmss").format(new Date());
    String userDir = System.getProperty("user.dir");
    nomePasta = className.replace("MOBILEX_AUTOMACAO.TEST.", "") + " " + dateName;

    new File(userDir + "\\target\\reports\\" + nomePasta);

    extent = new ExtentReports(userDir + "\\target\\reports\\" + nomePasta + "\\"
            + className.replace("MOBILEX_AUTOMACAO.TEST.", "") + "REPORT.html", true);
    extent.addSystemInfo("Nome APP", "MobileX");

    extent.loadConfig(new File(userDir + "\\extent-config.xml"));

}

@AfterMethod
public void getResult(ITestResult result) throws Exception {

    if (result.getStatus() == ITestResult.FAILURE) {
        String screenshotPath = getScreenhot(result.getName());
        logger.log(LogStatus.FAIL, "Test Case Failed is " + result.getThrowable());
        logger.log(LogStatus.FAIL, "Test Case Failed is " + result.getName());

        logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath));
    } else if (result.getStatus() == ITestResult.SUCCESS) {
        logger.log(LogStatus.PASS, "Test Case passed is " + result.getName());
    }

    extent.endTest(logger);
    DriverFactory.killDriver();
}

@AfterTest
public void endReport() throws IOException {

    extent.flush();
    extent.close();

}

My testing project is for Mobile, I am using TestNG, version 6.10 for my Java tests, with Appium version 7.0.

Author: M.Amaral, 2019-08-02

1 answers

If you change this:

@AfterTest
public void endReport() throws IOException {
    extent.flush();
    extent.close();
}

For this:

@AfterTest(alwaysRun = true)
public void endReport() throws IOException {
    extent.flush();
    extent.close();
}

It will passsar in flush and close, including you can use also in @AfterMethod. Following is the documentation: TestNG

 1
Author: Spencer Melo, 2019-08-23 22:58:45