'Taking screenshots for Allure reports from custom TestNG listener - TestListenerAdapter

I'm implementing custom test listener called TestListenerAdapter in my project and I wrote the code to capture screenshot in onTestFailure method of listener class. I also created following method and i'm calling in OnTestFailure method:

@Attachment(type = "image/png")
private byte[] createAttachment() {
    return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}

public void onTestFailure(ITestResult result)
{
  createAttachment();
}

The above method is not attaching the screenshots to Allure reports.

If we call createAttachment() method in @Test method then only screenshots are being added to allure reports. Adding screenshot method in each and every @Test is hectic task, so i've implemented this method in TestNG listener so that screenshot is captured whenever a test case is failed.

Please let me know if there is a way to use above mentioned createAttachment() method from onTestFailure() method of TestListenerAdapter listener.



Solution 1:[1]

For Allure listener to work with TestNG you have 2 options:

  1. Use an annotation on your test class:
    @Listeners(MyAllureListener.class)
    public class MyTestClass() {
       ...
    }
    
  2. Use Java Service Provider Interface (SPI) like this: enter image description here

filename has to match a listener package.classname that you extend. This file has to include a package.classname line pointing to your Listener class, i.e. com.test.MyListener

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moro