</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

What is the use of @Listeners annotation in TestNG?

@Listeners annotation on a test class tells TestNG to use a specific custom listener class for that test class.

Answer

@Listeners Annotation in TestNG

The @Listeners annotation is used at the class level to attach a custom listener to a specific test class, without needing to declare it in testng.xml.

Steps to use @Listeners:

Step 1 — Create the Listener class (implements ITestListener):

Java
package testnglisteners;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class Mylisteners implements ITestListener {

    @Override
    public void onTestStart(ITestResult result) {
        System.out.println(" test is started");
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        System.out.println(" test is passed");
    }

    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println("test is failed");
    }

    @Override
    public void onTestSkipped(ITestResult result) {
        System.out.println("test is skipped");
    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) { }

    @Override
    public void onStart(ITestContext context) { }

    @Override
    public void onFinish(ITestContext context) { }
}

Step 2 — Apply @Listeners to the test class:

Java
package testnglisteners;

import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners(testnglisteners.Mylisteners.class)
public class LoginTest {

    @Test
    void setup() {
        Assert.fail(); // This will trigger onTestFailure
    }

    @Test
    void loginByEmail() {
        Assert.assertTrue(true); // This will trigger onTestSuccess
    }

    @Test(dependsOnMethods = {"setup"})
    void loginByFacebook() {
        Assert.assertTrue(true); // Will be skipped since setup fails
    }
}

@Listeners vs testng.xml listener:

ApproachScopeWhen to use
@Listeners on classSingle classTargeted listener for specific tests
testng.xml listenerEntire suiteGlobal listener for all tests

Multiple listeners:

Java
@Listeners({testnglisteners.Mylisteners.class, testnglisteners.ReportListener.class})
public class LoginTest { }

Key point: We need to implement the ITestListener interface by creating a listener class of our own. After that, using the @Listeners annotation, we can specify that for a particular test class, our customized listener class should be used.

Follow AutomateQA

Related Topics