TestNG console output into log4j.log

2019-08-23 11:31发布

问题:

I need to get output result (FAIL or SUCCESS) into log4j output.

Assert.assertTrue(availresponse);

Is there any way to add TestNG console output into log4j.log file?

回答1:

I found a simple, easy and perfect way to log TestNG output into log4j.log file. But this can't be log Final Report Details into log4j (PASS or FAIL).

implements ITestListener

Then add unimplemented methods

public void onTestSuccess(ITestResult result) {
    logger.info(result);
}

public void onTestFailure(ITestResult result) {
    logger.info(result);
}

You can add log4j logger in the methods you need. Enjoy!



回答2:

If you need that, you could use if .. else construct to do the logging.

if(null != availresponse) {
   //log success message
} else {
   //log failure message
}

Another way is to write a custom class implementing TestListenerAdapter. You can see full example code here.



回答3:

Wrap the assert with a logger e.g.

log.info(Assert.assertNotNull(availresponse));

However this is a bit limited in terms of information. What I usually do is:

    if(availresponse==null)
{
log.fatal("availresponse was null");
}

Assert.assertNotNull(availresponse);

I know it's a bit of a hassle, testing for the condition twice but it does allow you to tweak the output level of the logger and add any other information you think would be useful e.g. the variables which were used to determine the contents of availresponse.

Alternatively you could try getting the console output to appear in your log file in which case you'll need to add something like:

log4j.appender.stdout.Target=System.out

to your log4j properties file.



回答4:

You can find test-output folder in your project PATH. index.html will show the Test output of Success or Fail.

  • If the testMethod() is Success, there will no any output result shows in index.html file. You can add Success message by using Reporter.log()

  • If testmethod() fail, automatically it will prints output in file.

    NOTE : java.lang.AssertionError is an error that thrown to indicate that an assertion has failed.


If anyone know how TestNG inserting that error to the report, comment below.



回答5:

Finally found the easiest way to log the Assert error in log4j
In catch block it should be Throwable, if it is Exception that will not work.

try {
    Assert.assertTrue(hotel.getAmenitiesList().size() < 0, "Hotel Amenities Available!");

} catch (Throwable e) {
    e.printStackTrace();
    logger.error("FAILED: testRoomAmenities ", e);
    Assert.fail();

When this implement that will not invoke as FAIL. It will show that scenario is PASSED. Therefore you should use Assert.fail() to make that is FAILED