Artur
Artur

Reputation: 803

How to use Log4j level depending on TestNG Assert result?

I am using TestNG and in the end of each my test there is an Assert validation.

Assert.assertEquals(true, mainPage.menu.isDisplayed());

How to log result of this operation using Log4j? If test failed - Log4j level is error, if test is passed - Log4j level is info.

Upvotes: 0

Views: 670

Answers (1)

Infern0
Infern0

Reputation: 2814

to achieve this, you have to implement the testng listeners. Information can be found here: http://testng.org/doc/documentation-main.html#testng-listeners

After you create a class that implements them, in the relevant method, you can put the logger with the proper level of logging.

Example:

public class TestNGListener implements ITestListener, ISuiteListener, IInvokedMethodListener {

    protected Logger logger = LogManager.getLogger(this.getClass());

    @Override
    public void onTestStart(ITestResult iTestResult) {

    }

    @Override
    public void onTestSuccess(ITestResult iTestResult) {

        logger.info("Test successfully executed.");
    }

    @Override
    public void onTestFailure(ITestResult iTestResult) {

        logger.error("Test Failed with message: " + iTestResult.getThrowable().getMessage());
    }
}

After that attach the listener to your testing class "or" if you have some complex structure of abstract pages will be good to be at the bottom.

Example:

@Listeners(TestNGListener.class)
public abstract class AbstractTest {
}

With the following configuration, you can receive the testng events specific for test/sutes/etc..

Good luck with it :)

Upvotes: 1

Related Questions