By Shakti P on May 27, 2016 8:09:34 AM
Logging is an important part of test execution, and informative/accessible logs help us to debug code effectively.
In this blog, I will discuss how to generate a test log with the help of TestNG Listeners.
What is the meaning of Listeners in TestNG?
To put it in non-technical terms TestNG manages everything through Suite, Test and Methods and the Listeners gives us the ability to act before and after every Suite, Test, and Method. To summarize TestNG provides us with multiple interfaces that extend org.testng.ITestNGListener. Each interface defines one aspect of TestNG.
To extend TestNG behavior we need to implement the TestNG-provided listener interface and then integrate it with TestNG.
Given below are some interfaces which we can use to generate custom test log:
- ITestListener Interface
- IInvokedMethodListener Interface
- IExecutionListener Interface
- ISuiteListener Interface
Methods of ITestListener Interface:
- onTestStart(): It runs only before the "@Test" method i.e. invoked each time before a test will be invoked.
- onTestSuccess(): It runs after the success of the "@Test" method i.e. invoked each time a test succeeds.
- onTestFailure(): It runs after the failure of the "@Test" method i.e. invoked each time a test fails.
Note: Inside onTestFailure()we can write any logic. For example, we can do a screenshot when a test fails.
- onTestSkipped(): It runs after the @Test method skipped i.e. invoked each time a test is skipped.
- onStart(): It run before the @BeforeTest method and before the “beforeInvocation” listener method i.e. invoked after the test class is initiated and before any configuration method is called.
- onFinish(): It runs after the @AfterTest method and after the “afterInvocation” listener method i.e. invoked after all the tests have run and all their configuration methods have been called.
- afterInvocation(): Listener gets invoked after a method is invoked by TestNG.. It runs before invocation of @Test, @BeforeTest, @BeforeSuite
- beforeInvocation(): Listener gets invoked before a method is invoked by TestNG. It runs before invocation of @Test, @AfterTest, @AfterSuite
Note: This listener will only be invoked for configuration and test methods.
- onExecutionStart(): It invokes before the TestNG starts running the suites.
- onExecutionFinish(): It invokes after TestNG is ends running all the test suites.
- onStart(): It runs before the @BeforeSuite and before the “beforeInvocation” listener method i.e. it invokes before TestNG starts running the suite.
- onFinish(): It runs before the @AfterSuite and before the “afterInvocation” listener method i.e. it Invoked after TestNG has run the suite.