如何在java中使用ExtentReports监听器打印日志?

时间:2017-06-14 10:54:08

标签: java selenium automation testng extentreports

这里我使用侦听器以HTML格式生成报告,但它不打印测试用例中的日志。

示例测试用例

@Test
public void testRedirectAllControlScreen() throws Exception {

    reportLog("login using a valid IsoMetrix username and password.");
    HomePage homePage = loginPage.login("username", "password");

    reportLog("Go to All Control page");
    AllControlPage allControlPage = homePage.navigateToControlPage();

    reportLog("Verify All Control page");
    allControlPage.verifyAllControlPage();

}

方法存在于BaseClass

 public void reportLog(String message) {
    message = BREAK_LINE + message;
    logger.info("Message: " + message);
    Reporter.log(message);
}

ExtentReport Listener

 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 + "ExtentReport.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.assignAuthor("360Log");
            test.setStartedTime(getTime(result.getStartMillis()));
            test.setEndedTime(getTime(result.getEndMillis()));

            for (String group : result.getMethod().getGroups())
                test.assignCategory(group);
            int s = result.getStatus();
            if (result.getStatus() == 1) {
                test.log(status, "Test " + status.toString().toLowerCase() + "ed");
            } else {
                String screen = BaseTest.screen;
                test.log(status, "Test " + status.toString().toLowerCase() + "ed " + test.addScreenCapture(screen));

            }
            extent.endTest(test);
        }
    }
  }

}

PFA截图。 It doesn't print logs step wise.

3 个答案:

答案 0 :(得分:2)

以下代码适用于我的范围报告版本:v2.41.1,试试!!!

尝试创建范围报告对象和记录器作为下面的代码。

// Base Class Usage
public static ExtentReports report;
public static ExtentTest logger;

report = new ExtentReports(path);       
report.loadConfig(new File("//home//.....//extent-config.xml"));

logger = report.startTest(this.getClass().getSimpleName()).assignCategory("Happy Path"));

// Test Case Usage: Using it at Every Step in Each Test Case
 logger.log(LogStatus.INFO,"String Message to Log for Each Step in Test Case");

// @AfterMethod
@AfterMethod(alwaysRun=true)
  public void TearDown_AM(ITestResult result) throws IOException
  {
      System.out.println("@After Method");
    try
    { 
        if(result.getStatus()==ITestResult.FAILURE)
        {
            String res = captureScreenshot(Driver, result.getName());
            String image= logger.addScreenCapture(res);
            System.out.println(image);
            String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
            logger.log(LogStatus.FAIL, TestCaseName  + logger.addScreenCapture(res));
            //  logger.log(LogStatus.FAIL, image, this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed");
        }
        else if(result.getStatus()==ITestResult.SUCCESS)
        {
            logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success and Title Verified"); 
        }
        else if(result.getStatus()==ITestResult.SKIP)
        {
            logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
        }
        report.endTest(logger);
        report.flush();

    }
    catch(Throwable t)
    {
        logger.log(LogStatus.ERROR,t.fillInStackTrace());
    }

  }

Logging in Extent Report Test Case Wise

答案 1 :(得分:1)

不使用监听器我能够实现同样的目标。 我根据人们的建议在 Baseclass.java 中实现了范围测试和范围报告:

public static ExtentTest test;
public static ExtentReports extent;

@BeforeSuite
public void before() {
    extent = new ExtentReports("target\\surefire-reports\\ExtentReport.html", true);
}

@BeforeMethod
public void setUp(Method method) throws Exception {
            test = extent.startTest(method.getClass().getSimpleName(),method.getClass().getEnclosingMethod().getName());
    test.assignAuthor("Vaibhav");
//Rest code will be generic for browser initiliazion.

}

@AfterSuite
public void tearDownSuite() {
    // reporter.endReport();
    extent.flush();
    extent.close();
}

//Method for adding logs passed from test cases
 public void reportLog(String message) {    
    test.log(LogStatus.INFO, message);//For extentTest HTML report
    logger.info("Message: " + message);
    Reporter.log(message);

}

示例测试用例

@Test
public void testRedirectAllControlScreen() throws Exception {

    reportLog("login using a valid IsoMetrix username and password.");
    HomePage homePage = loginPage.login("username", "password");

    reportLog("Go to All Control page");
    AllControlPage allControlPage = homePage.navigateToControlPage();

    reportLog("Verify All Control page");
    allControlPage.verifyAllControlPage();

}
  • ExtentReport视图

ExtentReport view

答案 2 :(得分:0)

我知道这个问题年代不长,但可能会对某人有所帮助。 将此代码用于buildTestNodes方法以打印TestNG日志-Reporter.log()。

public void buildTestNodes(IResultMap tests, LogStatus status) {
        //ExtentTest test = null;
        if (tests.size() > 0) {
            List<ITestResult> resultList = new LinkedList<ITestResult>(tests.getAllResults());
            class ResultComparator implements Comparator<ITestResult> {
                public int compare(ITestResult r1, ITestResult r2) {
                    return getTime(r1.getStartMillis()).compareTo(getTime(r2.getStartMillis()));
                }
            }
            Collections.sort(resultList , new ResultComparator ());

            for (ITestResult result : resultList) {
                test = extent.startTest(result.getMethod().getMethodName());
                test.getTest().setDescription(result.getMethod().getDescription());
                test.getTest().setStartedTime(getTime(result.getStartMillis()));
                test.getTest().setEndedTime(getTime(result.getEndMillis()));
                for(String message:Reporter.getOutput(result)){    **//This code picks the log from Reporter object.**
                    test.log(LogStatus.INFO, message);
                }
                for (String group : result.getMethod().getGroups())
                test.assignCategory(group);
                String message = "Test " + status.toString().toLowerCase() + "ed";
                if (result.getThrowable() != null)
                message = result.getThrowable().getClass() +": "+ result.getThrowable().getMessage();
                test.log(status, message);
                extent.endTest(test);
            }
        }
    }