Thursday, October 18, 2012

WebDriver - Take Screenshots on Test Case Fail.

There are two way you can achieve this if you are using TestNG as you unit testing framework. Refer the following blog post to see how to do this using TestNG.

Below we will discuss how to do the same thing using WebDriver listeners. Webdriver has a WebDriverEventListener interface which you can implement and override the particular listener you want. WebDriverEventListener interface has onException method which is being called whenever a WebDriver exception occurs, So we will override this method and will write down the code to take screenshot in it.
you need to implement all the methods of the WebDriverEventListener class, here I haven't show that to make code looks small.
import org.openqa.selenium.*;

 * Implements WebDriverEventListener and overrides onException method
 * @author Gaurang
public class WebDriverEventListenerDemo implements WebDriverEventListener {
 public void onException(Throwable exception, WebDriver driver) {
  File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  try {
   FileUtils.copyFile(screenShot, new File("c:\\tmp\\exception.png"));
  } catch (IOException e) {
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

 * Class registers the Event listern class we created 
 * @author gshah
public class TestWithEvenRegistered {
 WebDriver driver = new FirefoxDriver();
 EventFiringWebDriver eventFiringWebDriver;
 public void setup() {
  eventFiringWebDriver = new EventFiringWebDriver(driver);
  eventFiringWebDriver.register(new WebDriverEventListenerDemo());
  * "qq" is wrong element id and so NoElementFound Exception will 
  * be generated, which will call our overridden method of WebDriverEventListenerDemo
  * class and will take the screenshot. 
 public void test(){


Pradeep Sundaram said...

onException method is not called on NoSuchElementException

Anonymous said...

Hi in the code above the 3rd line has onException function span something like html code is used is used. What for it is used, and when i use this code of line im getting error like -- Syntax error on tokens, delete these tokens

Post a Comment