The Selenium WebDriver provides the EventFiringWebDriver
class, which listens to various events happening during the test execution. For example, events are raised when we navigate to a page, when a click is performed on an element, or value is changed. The following table lists all the events that we can track during the test execution:
We can use these event handlers to process extra commands. For example, before entering a value into a textbox, we can clear the existing value or capture a screenshot even if an exception is raised by WebDriver
. This is done with the following steps:
EventFiringWebDriver
instance using WebDriver
instanceEventFiringWebDriver
instanceThe event listener class can be created in two ways:
WebDriverEventListener
interfaceAbstractWebDriverEventListener
classIn this recipe, we will see how to use EventFiringWebDriver
to listen to the WebDriver
events.
Create a new test that will get an instance of WebDriver
, navigate to a site, and perform some basic actions and verifications.
First, we will define an event listener class by implementing the WebDriverEventListener
interface in the following way:
package com.secookbook.examples.chapter04; import org.openqa.selenium.*; import org.openqa.selenium.support.events.WebDriverEventListener; public class MyListener implements WebDriverEventListener { public void beforeChangeValueOf(WebElement element, WebDriver driver) { element.clear(); } }
Next, we will create a test that uses EventFiringWebDriver
:
package com.secookbook.examples.chapter04; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.events.EventFiringWebDriver; import org.junit.After; import org.junit.Before; import org.junit.Test; public class EventFiringTest { private WebDriver driver; @Before public void setUp() throws Exception { driver = new FirefoxDriver(); } @Test public void testEventFiringWebDriver() throws Exception { EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver); MyListener myListener = new MyListener(); eventDriver.register(myListener); eventDriver.get("http://bit.ly/1DbdhsW"); eventDriver.findElement(By.id("q")) .sendKeys("Selenium Testing Tools Cookbook"); } @After public void tearDown() throws Exception { driver.quit(); } }
Let's add one more event handler to the event listener class to capture a screenshot when an exception is thrown:
public void onException(Throwable exception, WebDriver driver) { try { if (driver.getClass().getName().equals("org.openqa.selenium.remote.RemoteWebDriver")) { driver = new Augmenter().augment(driver); } File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File("target/screenshots/error.png")); } catch (Exception e) { e.printStackTrace(); } }
18.118.27.119