Implementing the ITestListener interface

For this, let's understand a very simple program. We create a very simple listener first.

We have implemented the ITestListener and four of the methods, which are:

  • onTestStart
  • onTestSuccess
  • onTestFailure
  • onTestSkipped

The following code shows the implementation of ITestListener:

public class SampleListener implements ITestListener {
@Override
public void onTestStart(ITestResult result) {
System.out.println("The test that has started is: " + result.getName());
}
@Override
public void onTestSuccess(ITestResult result) {
System.out.println("The test that has passed is: " + result.getName());
}
@Override
public void onTestFailure(ITestResult result) {
System.out.println("The test that has failed is: " + result.getName());
}
@Override
public void onTestSkipped(ITestResult result) {
System.out.println("The test that has skipped is: " +
result.getName());
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult
result) {
}
@Override
public void onStart(ITestContext context) {
}
@Override
public void onFinish(ITestContext context) {
}
}

question now arises: how do we use this listener to log messages and generate reports?

For this, we need to create a test class, as shown here:

@Listeners(org.packt.listeners.SampleListener.class)
public class ListenerClass {
@Test
public void checkListeners() {
System.setProperty(
"webdriver.chrome.driver",
System.setProperty("user.dir")+"\src\main\resources\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.freecrm.com");
System.out.println("Title is : " + driver.getTitle());
}
}

When we right-click on this code and select Run As | TestNG Test, we get the following output:

The test that has started is: checkListeners
Title is : #1 Free CRM software in the cloud for sales and service
The test that has passed is: checkListeners
PASSED: checkListeners

Another way to use the listener class along with the test class is to use it as a tag in TestNG XML. For this, we just need to add the following tag in the TestNG XML file:

<listener class-name="SampleListener"></listener>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset