Before getting into the sample code, lets have a look on EventFiringWebDriver, WebDriverEventListener, and AbstarctWebDriverEventListener descriptions.

  • EventFiringWebDriver is a class and wrapper around an arbitrary webdriver instance which supports registering of a WebDriverEventListener.
  • WebDriverEventListener is interface which includes list of abstract events methods and all should be implemented if we are implementing it.
  • AbstarctWebDriverEventListener is abstract class which has implemented WebDriverEventListener interface. We can extend this class if we are only interested in some events. All methods provided by this class have an empty method body.

So we can choose between EventFiringWebDriver and AbstarctWebDriverEventListener according to our needs.

Note: I have used AbstarctWebDriverEventListener class in below example.

Let’s have a look on example-

Create a class file and extends AbstarctWebDriverEventListener class-
public class WebDriverEventListenerClass extends AbstractWebDriverEventListener {
@Override
public void onException(Throwable arg0, WebDriver driver) {

File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File(“c:\\tmp\\exception.png”));
} catch (IOException e) {
e.printStackTrace();
}}}

Create another class file and register WebDriverEventListenerClass file as it has implemented onException event method-

public class EventFiringDriverExample {
@Test
public void Events(){
System.setProperty(“webdriver.ie.driver”, “D:/Training/IE_Driver/IEDriverServer.exe”);

WebDriver driver = new InternetExplorerDriver();

// Creating EventFiringWebDriver instance

EventFiringWebDriver eventFiringDriver= new EventFiringWebDriver(driver);

// Creating instance of eventListener, that we just defined
eventFiringDriver.register(new WebDriverEventListenerClass());

eventFiringDriver.get(“https://www.google.co.in/”);

eventFiringDriver.findElement(By.className(“nosuchelement”));

}}

Once you run ‘Events()’ method, it will open Google and search for element which is not available. In this case, method will throw WebElementNotFound exception and system will capture the screenshot and save it at “c:\\tmp\\exception.png” location..

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s