Custom Listeners in testng using ITestListener

Other than TestListenerAdapter we can even implement an interace named ITestListener for our class named CustomListener. And since we are extending an interface this time we have to override all the functions in that interface .Please note we can customize some of the methods from the iTestAdapter interface and we can leave other methods as defualt as well.

public class CustomListener implements ITestListener{        

    @Override        
    public void onFinish(ITestContext arg0) {                    
        // TODO Auto-generated method stub                
         }        

    @Override        
    public void onStart(ITestContext arg0) {                    
        // TODO Auto-generated method stub                
     }        

    @Override        
    public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {                    
        // TODO Auto-generated method stub                
    }        

    @Override        
    public void onTestFailure(ITestResult tr) {                    
  System.out.println("Test failed " + tr.getName()
   }        

    @Override        
    public void onTestSkipped(ITestResult tr) {                    
       System.out.println("Test skipped " + tr.getName()
    }        

    @Override        
    public void onTestStart(ITestResult tr) {                    
  System.out.println("Test started " + tr.getName()
                
    }        

    @Override        
    public void onTestSuccess(ITestResult succes) {                    
        System.out.println("Test success " + tr.getName()
     }        
}        

Then we need to attach this listener to our test case classes.There are two ways of doing It.

In first method we can define our listener in testing.xml file like below.

<listeners>
<listener class-name="CustomReport.CustomReporting" />
</listeners>

One more but less preferred method is to use @Listener at class level.

This listener will be available at the class level and will be available for all test case methods of the class.

@Listeners(CustomReport.CustomReporting)            
    public class MyTestCase {    

Only problem with this approach is that if we have 100 classes we have to copy paste this listener in each of those classes.

So better way is to use first method as there we have to add or remove the listener only at one place in the xml file.