Selenium- Capture screenshot using TestNG ITestListeners

Every automation test is expected to capture screenshot when any failure happened. Luckily, Selenium provides method to capture screenshot and Testng provides useful listeners which manages the test events.
In this tutorial, we will learn how to capture screenshot on test failure using Testng listeners. Each step is explained in detail explanation.
Refer below for step by step explanation:

Pre-Requisite:

It will be great if you complete following steps:

  1. Java should be installed ( If Java is not installed then click on the link (Install & Setup Java)
  2. Selenium TestNG Project should be set up (Refer link if Selenium TestNG project is not set up – Setup Selenium TestNG)
  3. Basic understanding of the Screenshot Capture method (Refer our blog if you need to understand the Basics of Screenshot capture)

Once after completion of pre-requisite we need to write few classes for following purposes:

  1. Base Class: In Base class, we need to write the most frequent methods and variable which we need to use across multiple classes. In this tutorial, we declared a static WebDriver by extending the Base Class.
  2. TestngListeners Class: This class implemented ITestListener methods and write screenshot capture code in on test failure.
  3. Test Class (captutreScreenShotonFailure): Create a test class and write assertion code.

Step 1: Open Eclipse and Selenium Project and create one Base class. Declare static WebDriver instance which can use across different classes.
Refer below for Base class Code:

package com.thoughcoders.automation;
import org.openqa.selenium.WebDriver;

public class Base {
public static WebDriver driver;
}

Step 2: Create test class captutreScreenShotonFailure, extend Base class to utilize WebDriver driver and write test method:
Refer below for captutreScreenShotonFailure class code:

package com.thoughtcoders.automation.test;

import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com. thoughtcoders.automation.Base;
import io.github.bonigarcia.wdm.WebDriverManager;

public class captutreScreenShotonFailure extends Base {
	
@Test
public void HomePageTest() {
		WebDriverManager.chromedriver().browserVersion("83.0").setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://thoughtcoders.com/");
System.out.println("Title of WebPage: "+ driver.getTitle());
Assert.assertEquals("aThoughtCoders | Web Development, Automation,"
 + " QA Training", driver.getTitle());
driver.close();
}
		
}

Step 3: Create a class to implement TestNG Listeners (TestngListeners) and implement ITestListner methods.
ITestListner: ITestListeners is the most popular TestNG interface which provides a very useful set of methods and by implementing these methods we perform the action on the Test Events. Refer below for the list of ITestListners
Override method on test failure and write code to capture screenshot and save in root. (If you need a detail explanation of the screenshot capture code then refer link – https://thoughtcoders.com/blog/capture-screenshots-using-selenium-webdriver/
)

@Override
public void onTestFailure(ITestResult arg0) {
try {
File file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file, new File(System.getProperty("user.dir")+File.separator + 
				arg0.getName()+"_"+arg0.getEndMillis()+".png"));
System.out.println("*******Screenshot captured********");
} 
catch(Exception e) {
e.printStackTrace();
}
}

Step 5: Open Testng.xml and add the below step to integrate TestNG listeners.

Complete testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<listeners>
<listener class-name="listeners.TestngListeners"/>
</listeners>
  <test thread-count="5" name="Test">
    <classes>
      <class name="com.qaedupoint.automation.test.captutreScreenShotonFailure"/>
    </classes>
  </test> <!-- Test -->
</suite> <!-- Suite -->

Step 6- Run Test class explicitly- To run the test use @Listeners(className.class) annotation and pass the class name as an argument.
@Listeners(listeners.TestngListeners.class)

Listeners annotation usage

Step 7: Run Testng.xml and perform test.
As assertions are knowingly failed to so screenshot is captured and save into project root folder.
Console output:
Title of WebPage: ThoughtCoders | Web Development, Automation, QA Training
Screenshot captured*
Suite
Total tests run: 1, Failures: 1, Skips: 0
After test execution, right click on project and refresh. Now captured screenshot visible and saved into project root directory.

Output: Screenshot file

Congratulations, you have successfully captured screenshot on test failure. Feel free to contact us on query@thoughtcoders.com if you face any issue or need more information.

Subscribe to our Newsletter:

How to take screenshots using Selenium WebDriver

Capture screenshot in Selenium:

The screenshot is one of the most frequent activities of testing. The screenshot shot is always taken to capture important details or record specific event during testing. Generally, most of us capture a screenshot on test failure. This tutorial explains how to capture screenshot and store at the specific directory.
This tutorial provides step by step detailed explanation of each step and details of methods provided by Selenium WebDriver. Refer below for step by step implementation.

Read More How to take screenshots using Selenium WebDriver

Selenium with TestNG Setup Tutorial

What is TestNG Framework & How to Setup or Install TestNG Selenium Framework?

TestNG is a testing framework inspired by JUnit & NUnit with many additional features that makes it even more powerful & can help in designing a more robust automation testing framework.

TestNG is designed to cover all categories of tests:  unit, functional, end-to-end, integration, etc…

And, In this TestNG tutorial of ThoughtCoders you will learn “How to install and setup TestNG Selenium Framework” using Java? with step by step process and with a sample TestNG Selenium Framework.

Read More Selenium with TestNG Setup Tutorial

Scenario Outline and Examples in BDD Cucumber

What is Scenario Outline and Example in Cucumber BDD Frameworks

Data Driven testing is very genuine expectations from any automation framework. To perform data driven testing in BDD framework we need to use scenario outline and examples. To help automation community, we created this tutorial.

In this tutorial we will learn about Scenario Outline and Examples. Scenario Outline gives us flexibility to perform data driven testing in BDD Framework. In simpler words it allows us to perform same test over multiple data.

Read More Scenario Outline and Examples in BDD Cucumber