How to capture screenshot for failed test cases in Selenium Webdriver?

Welcome to Free Training Tutorials, we have discussed how to capture snapshot screenshot in Selenium webdriver.

It is not enough to be able to write a Selenium Webdriver script, anyone can design that nowadays. We must design the script in such a way that we can utilize script code as much as possible.  In this tutorial, we will discuss how to take a screenshot for failed test cases in Selenium.

Situations where Script can fail

1) If the script encounters an issue (such as a locator has been changed or the application has been changed), we will need to maintain the Selenium script.

2) Due to application issue: In this situation, we must notify the appropriate point of contact, either the manual tester or the developer.

Capture screenshot in selenium for failed test cases

In our previous tutorial, we covered how to take a free-form screenshot in Selenium. If you have not gone through the previous tutorial, we highly recommend you to go through it.

In this tutorial, we will explore how to take a screenshot for failed test cases in Selenium Webdriver.

EventFiringWebDriver

The EventFiringWebDriver class is a wrapper around the WebDriver that allows the driver to fire events.

EventListener

The EventListener class waits for the EventFiringWebDriver to be available and handles all events that are dispatched. To create an instance of EventListener, There are two ways:

a. By implementing the WebDriverEventListener interface.

b. By extending the AbstractWebDriverEventListener class provided in the WebDriver library.

The EventFiringWebDriver class can have more than one listener waiting to hear about an event. All event listeners need to register with the class to get notified.

AbstractWebDriverEventListener methods

In this tutorial, we are going to use AbstractWebDriverEventListener abstract class. But how? We will discuss in a couple of mins. Let’s have a look at different methods of AbstractWebDriverEventListener.

  1. afterAlertAccept​(WebDriver driver)
  2. afterAlertDismiss​(WebDriver driver)
  3. afterChangeValueOf​(WebElement element, WebDriver driver, java.lang.CharSequence[] keysToSend)
  4. afterClickOn​(WebElement element, WebDriver driver)
  5. afterFindBy​(By by, WebElement element, WebDriver driver)
  6. afterGetScreenshotAs​(OutputType<X> target, X screenshot)
  7. afterGetText​(WebElement element, WebDriver driver, java.lang.String text)
  8. afterNavigateBack​(WebDriver driver)
  9. afterNavigateForward​(WebDriver driver)
  10. afterNavigateRefresh​(WebDriver driver)
  11. afterNavigateTo​(java.lang.String url, WebDriver driver)
  12. afterScript​(java.lang.String script, WebDriver driver)
  13. afterSwitchToWindow​(java.lang.String windowName, WebDriver driver)
  14. beforeAlertAccept​(WebDriver driver)
  15. beforeAlertDismiss​(WebDriver driver)
  16. beforeChangeValueOf​(WebElement element, WebDriver driver, java.lang.CharSequence[] keysToSend)
  17. beforeClickOn​(WebElement element, WebDriver driver)
  18. beforeFindBy​(By by, WebElement element, WebDriver driver)
  19. beforeGetScreenshotAs​(OutputType<X> target)
  20. beforeGetText​(WebElement element, WebDriver driver)
  21. beforeNavigateBack​(WebDriver driver)
  22. beforeNavigateForward​(WebDriver driver)
  23. beforeNavigateRefresh​(WebDriver driver)
  24. beforeNavigateTo​(java.lang.String url, WebDriver driver)
  25. beforeScript​(java.lang.String script, WebDriver driver)
  26. beforeSwitchToWindow​(java.lang.String windowName, WebDriver driver)
  27. onException​(java.lang.Throwable throwable, WebDriver driver)

AbstractWebDriverEventListener has plenty of events method, but in this tutorial, we will use only onException method. So, whenever the test script fails or any exception occurs,  onException will handle the failure event. To get our objective (capture screenshot when script fails), we will keep the capture snapshot code under  onException method and save it.

Tasks

we will use Java main method, not any framework like Junit or TestNG. Here are tasks what we will perform.

  1. Initialize the webdriver instance with ChromeDriver.
  2. Maximize browser window.
  3. Open site http://demo.itlearn360.com
  4. Creating instance of EventFiringWebDriver by passing webdriver.
  5. Registering Exception event
  6. Keeping snapshot capture code inside onException method.
  7. Finding element with EventFiringWebDriver instance with wrong xpath to generate exception.
  8. Close the browser.

Webdriver Script

package testing.org;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;
import org.openqa.selenium.support.events.EventFiringWebDriver;
public class TakeExceptionSnapshot {
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		System.setProperty("webdriver.chrome.driver", "C:\\Users\\Jayant\\Pictures\\qatraininimages\\chromedriver_win32\\chromedriver.exe");
		WebDriver browserObject = new ChromeDriver();
		browserObject.manage().window().maximize();
		browserObject.get("http://demo.itlearn360.com/");
		browserObject.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS) ;
    	
    	EventFiringWebDriver eventDriver = new EventFiringWebDriver(browserObject).register(new AbstractWebDriverEventListener() {

    		  @Override
    		  public void onException(Throwable throwable, WebDriver browser) {

    		    // Take the screenshot using the Webdriver.
    		    File screen = ((TakesScreenshot)browserObject).getScreenshotAs(OutputType.FILE);

    		    // Now you can copy the screenshot somewhere on your system.
    		    try {
					FileUtils.copyFile(screen, new File("C:\\project\\exception.png"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		  }
    		});

    		try {

    			eventDriver.findElement(By.xpath("//*[@id=\"loginlabel\"]/div[1]/p/a")).click();
    		} catch (NoSuchElementException e) {   
    		  // Triggering point for the <onException> event.
    			eventDriver.close();
    		}
    	browserObject.quit();
	}
}


 

Instructor-led Training

https://www.qaonlinetraining.com/programs/master-of-functional-automation-testing/

Conclusion

This is the way the to capture the snapshot for failed test cases. You can use this script in your project implementation, or you can face this problem in your interview.