Search code examples
javaseleniumtestngextentreports

Get log message from Assertions


I'm integrating html-reports to our test framework using Extent Report library (version 4).

For that purpose I wrote a wrapper, that encapsulates our default TestNG logger (for the console output) and ExtentReport logger (ExtentTest.log, to collect data for html-report). We use TestNg as our testing framework.

Having an issue capturing log messages from failed assertions (both soft and hard Assertions) to display it in html-report, they go only to the console log. What would be the possible solution to capture those Assert log messages to show them in html-report?

I can't extend Assert (or SoftAssert) classes and add my own implementation (by adding an instance of ExtentTest.log there) because I'd have to replace all assertions in dozens of tests.

public class Loggers {
  private static final Loggers instance = new Loggers();
  private static ExtentTest test;
  private static ExtentReports extent;
  private static Logger LOG;
  private static final String REPORT_LOCATION = "test-output/reports.extent.html";

  /**
   * Returns an instance of {@link ExtentReports} object. If it doesn't exist creates a new instance and returns it
   */
  public static ExtentReports getLogger() {
    if ( extent == null ) {
      createInstance();
    }
    return extent;
  }

  /**
   * Create ExtentReport and attaches htmlReporter to it
   */
  public static void createInstance() {
    ExtentHtmlReporter htmlReporter = getHTMLReporter();
    extent = new ExtentReports();
    extent.attachReporter( htmlReporter );
  }

  /**
   * This method creates, configures and returns an instance of ExtentHtmlReporter
   *
   */
  public static ExtentHtmlReporter getHTMLReporter() {
    ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter( REPORT_LOCATION );
     return htmlReporter;
  }

  /**
   * This method logs a message with the INFO level for both instances of TestNG Logger and ExtentTest
   */
  public void info( String message ) {
    LOG.info( message );
    test.log( Status.INFO, message );
  }

Solution

  • Found the solution. Will post here if somebody will have similar issue.

    If you locate your loggers in a listener class, you can put your logger over there and use ITestResult as an argument, specifically its method getThrowable (It returns the throwable that was thrown while running the method)

     /**
       * Triggered upon the failure of a test
       */
      public void onTestFailure( ITestResult testResult ) {
          LOG.fail( testResult.getThrowable() );
     }
    

    It will print in the report a failed assertion or thrown exception.