The EventFiringWebDriver class

The EventFiringWebDriver class is a sort of API that encloses arbitrary WebDriver instances to register WebDriverEventListener; it provides an automatic system to trigger events. For example, whenever a test failure occurs, the automatic screen capture method gets activated and starts logging screenshots. The EventFiringWebDriver class is highly recommended for better reporting and test maintenance. Through EventFiringWebDriver, the user can have full control over the web page under test, including control over navigation, over finding elements, on exception, the click action, over script execution, and so on.

Follow these regulations to run tests through EventFiringWebDriver:

  1. Create a Listeners class by either implementing the WebDriverEventListener interface or extending the AbstractWebDriverEventListener class:
    public class Listeners extends AbstractWebDriverEventListener 
    {...
    }
    
    public class Listeners implements WebDriverEventListener 
    {...
    }
  2. Now, create a test class and initialize EventFiringWebDriver (termed eventDriver in the following examples):
    private WebDriver driver;
    EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver);
  3. Finally, register the WebDriver event listener with EventFiringWebDriver:
    Listeners EL = new Listeners();
    eventDriver.register(EL);
    eventDriver.get("http://www.yourwebsite.com");

The user-defined WebDriver event listener functions are easily customizable and play a major role by responding to events. Let's discuss EventFiringWebDriver functions further, as follows:

  • afterNavigateBack(): The afterNavigateBack() method is triggered soon after executing the navigate().back() command. The following is the syntax for this method:
    afterNavigateBack(WebDriver driver)

    In the following code snippet, the afterNavigateBack() method prints the web page's current URL after navigating back from the previous URL:

    @Override
    public void afterNavigateBack(WebDriver driver) {
    System.out.println("After Navigating Back. I'm at "
     + driver.getCurrentUrl());
    }
  • afterNavigateForward(): The afterNavigateForward() method is triggered soon after executing the navigate().forward() command. The following is the syntax for this method:
    afterNavigateForward(WebDriver driver)

    In the following code snippet, it prints the web page's current URL after navigating towards the previously visited URL:

    @Override
    public void afterNavigateForward(WebDriver driver) {
    System.out.println("After Navigating Forward. I'm at "
     + driver.getCurrentUrl());
    }
  • afterNavigateTo(): The afterNavigateTo() method is triggered soon after executing the get(String url) or navigate().to(String url) commands. The following is the syntax for this method:
    afterNavigateTo(java.lang.String url, WebDriver driver)

    In the following code snippet, it prints the web page's current URL after visiting or opening a web page:

    @Override
    public void afterNavigateTo(String url, WebDriver driver) {
      System.out.println("After Navigating To: " + url + ", my url is: "    + driver.getCurrentUrl());
    }
  • beforeNavigateBack(): The beforeNavigateBack() method is triggered just before executing the navigate().back() command. The following is the syntax for this method:
    BeforeNavigateBack(WebDriver driver)

    In the following code snippet, it prints the web page's current URL before navigating back from the previous URL:

    @Override
    public void beforeNavigateBack(WebDriver driver) {
      System.out.println("Before Navigating Back. I was at "
        + driver.getCurrentUrl());
    }
  • beforeNavigateForward(): The beforeNavigateForward() method is triggered just before executing the navigate().forward() command. The following is the syntax for this method:
    beforeNavigateForward(WebDriver driver)

    In the following code snippet, it prints the web page's current URL before navigating towards the previously visited URL:

    @Override
    public void beforeNavigateForward(WebDriver driver) {
      System.out.println("Before Navigating Forward. I was at "
        + driver.getCurrentUrl());
    }
  • beforeNavigateTo(): The beforeNavigateTo() method is triggered just before executing the get(String url) or navigate().to(String url) commands. The following is the syntax for this method:
    beforeNavigateTo(java.lang.String url, WebDriver driver)

    In the following code snippet, it prints the web page's current URL before visiting or opening a web page:

    @Override
    public void beforeNavigateTo(String url, WebDriver driver) {
      System.out.println("Before Navigating To : " + url + ", my url was: "    + driver.getCurrentUrl());
    }
  • afterClickOn(): The afterClickOn() method is triggered soon after executing the WebElement.click() command. The following is the syntax for this method:
    afterClickOn(WebElement element, WebDriver driver)

    In the following code snippet, the afterClickOn() method prints the most recently clicked element:

    @Override
    public void afterClickOn(WebElement element, WebDriver driver) {
    System.out.println("Clicked Element with: '" + element + "'");
    }
  • beforeClickOn(): The beforeClickOn() method is triggered just before executing WebElement.click() command. The following is the syntax for this method:
    beforeClickOn(WebElement element, WebDriver driver);

    In the following code snippet, the element likely to be clicked is highlighted just before executing the click() function:

    @Override
    public void beforeClickOn(WebElement element, WebDriver driver) {
      System.out.println("Trying to click: '" + element + "'");
      /** Highlight Elements before clicking **/
      for (int i = 0; i < 1; i++) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: black; border: 3px solid black;");
      }
    }
  • afterFindBy(): The afterFindBy() method is triggered soon after executing the WebElement.findElement(), WebElement.findElements(), driver.findElement(), or driver.findElements() command. The following is the syntax for this method:
    afterFindBy(By by, WebElement element, WebDriver driver);

    In the following code snippet, afterFindBy() prints the element soon after locating it:

    private By finalFindBy;
    @Override
    public void afterFindBy(By by, WebElement element, WebDriver driver) {
      finalFindBy = by;
      System.out.println("Found: '" + finalFindBy + "'.");
      // This is optional or an alternate method
      System.out.println("Found: " + by.toString() + "'.");
    }
  • beforeFindBy(): The beforeFindBy() method is triggered just before executing the WebElement.findElement(), WebElement.findElements(), driver.findElement(), or driver.findElements() command. The following is the syntax for this method:
    beforeFindBy(By by, WebElement element, WebDriver driver);

    In the following code snippet, the beforeFindBy() method prints the element just before locating it:

    private By finalFindBy;
    @Override
    public void beforeFindBy(By by, WebElement element, WebDriver driver) {
      finalFindBy = by;
      System.out.println("Trying to find: '" + finalFindBy + "'.");
      System.out.println("Trying to find: " + by.toString()); // This is optional or an alternate method
    }
  • afterScript(): The afterScript() method is triggered soon after executing the RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[]) command. The following is the syntax of this method:
    afterScript(java.lang.String script, WebDriver driver)

    In the following code snippet, afterScript() prints a successful message soon after executing the JavaScript function:

    @Override
    public void afterScript(String script, WebDriver driver) {
      System.out.println("JavaScript is Executed");
    }
  • beforeScript(): The beforeScript() method is triggered just before executing the RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[]) command. The following is the syntax for this method:
    beforeScript(java.lang.String script, WebDriver driver)

    In the following code snippet, beforeScript() prints a foretelling message, saying that the JavaScript is about to be executed:

    @Override
    public void beforeScript(String script, WebDriver driver) {
      System.out.println("JavaScript is about to execute");
    }
  • afterChangeValueOf(): The afterChangeValueOf() method is triggered soon after executing the WebElement.clear() or WebElement.sendKeys() command. The following is the syntax of this method:
    afterChangeValueOf(WebElement element, WebDriver driver);

    In the following code snippet, this method prints the text field values available both before and after the Google search:

    private String actualValue;
    @Override
    public void afterChangeValueOf(WebElement element, WebDriver driver) {
      String modifiedValue = "";
      try {
        modifiedValue = element.getText();
      } catch (StaleElementReferenceException e) {
    System.out.println("Could not log change of element, because of a stale" + " element reference exception.");
        return;
      }
    
      // What if the element is not visible anymore?
      if (modifiedValue.isEmpty()) {
        modifiedValue = element.getAttribute("value");
      }
    
    System.out.println("The value changed from '" + actualValue + "' to '" + modifiedValue + "'");
    }
  • beforeChangeValueOf(): The beforeChangeValueOf() method is triggered just before executing the WebElement.clear() or WebElement.sendKeys() command. The following is the syntax of this method:
    beforeChangeValueOf(WebElement element, WebDriver driver)

    In the following code snippet, this method prints the value that exists before clearing the Google search field:

    private String actualValue;
    @Override
    public void beforeChangeValueOf(WebElement element, WebDriver driver) {
      actualValue = element.getText();
    
      // What if the element is not visible anymore?
      if (actualValue.isEmpty()) {
        actualValue = element.getAttribute("value");
      }
    
    System.out.println("The existing value is: " + actualValue);
    }
  • onException(): The onException() method is triggered whenever an exception is thrown during test execution. The following is the syntax of this method:
    onException(java.lang.Throwable throwable, WebDriver driver)

    In the following code snippet, the EventFiringWebDriver takes a screenshot soon after getting an exception thrown on test execution:

    @Override
    public void onException(Throwable throwable, WebDriver webdriver) {
    
      File scrFile = ((TakesScreenshot) webdriver)
        .getScreenshotAs(OutputType.FILE);
      try {
        org.apache.commons.io.FileUtils.copyFile(scrFile, new File("C:\Testfailure.jpeg"));
      } catch (Exception e) {
        System.out.println("Unable to Save");
      }
    }

Event-firing WebDriver example

Let's discuss this with an example by creating a Listener class, which is said to be an EventListener class. Here, we are extending the AbstractWebDriverEventListener class instead of implementing the WebDriverEventListener class; however, either class does the same job. Through EventListener, you can override any listeners as you wish and the events can be fired on any popular browsers; for example, the following class is named Listeners.java:

public class Listeners extends AbstractWebDriverEventListener {
  // public class Listeners implements WebDriverEventListener {
    private By finalFindBy;
    private String actualValue;

As discussed in the preceding functions with an exercise on each, there are different events that are triggered each time EventFiringDriver is executed. The following is a list of navigation functions with user-defined steps to perform an action:

/** URL NAVIGATION | navigate(), get() **/
// Prints the URL before Navigating to specific URL 
@Override
public void beforeNavigateTo(String url, WebDriver driver) {
System.out.println("Before Navigating To : " + url + ", my url was: " + driver.getCurrentUrl());
}

// Prints the current URL after Navigating to specific URL 
@Override
public void afterNavigateTo(String url, WebDriver driver) {
System.out.println("After Navigating To: " + url + ", my url is: " + driver.getCurrentUrl());
}

// Prints the URL before Navigating back "navigate().back()"
@Override
public void beforeNavigateBack(WebDriver driver) {
System.out.println("Before Navigating Back. I was at " + driver.getCurrentUrl());
}

// Prints the current URL after Navigating back from the previous URL
@Override
public void afterNavigateBack(WebDriver driver) {
System.out.println("After Navigating Back. I'm at " + driver.getCurrentUrl());
}

// Prints the URL before Navigating forward "navigate().forward()"
@Override
public void beforeNavigateForward(WebDriver driver) {
System.out.println("Before Navigating Forward. I was at " + driver.getCurrentUrl());
}

// Prints the current URL after Navigating forward "navigate().forward()"
@Override
public void afterNavigateForward(WebDriver driver) {
System.out.println("After Navigating Forward. I'm at " + driver.getCurrentUrl());
}

The following methods are automatically activated on locating an element. They help you to identify whether an element is available in a page or not:

/** FINDING ELEMENTS | findElement(), findElements() **/
// Called before finding Element(s)
 @Override
public void beforeFindBy(By by, WebElement element, WebDriver driver) {
  finalFindBy = by;
  System.out.println("Trying to find: '" + finalFindBy + "'.");
  System.out.println("Trying to find: " + by.toString()); // This is optional and an alternate way
}

 // Called after finding Element(s)
 @Override
public void afterFindBy(By by, WebElement element, WebDriver driver) {
  finalFindBy = by;
  System.out.println("Found: '" + finalFindBy + "'.");
  System.out.println("Found: " + by.toString() + "'."); // This is optional and an alternate way
 }

The following are used to debug and are also helpful during an ongoing presentation. Every testing scenario involves clicking on a link and verifying the expected page; EventFiringWebDriver does more than an ordinary click() function would do, as shown in the following code:

/** CLICK | click() **/
// Called before clicking an Element
@Override
public void beforeClickOn(WebElement element, WebDriver driver) {
  System.out.println("Trying to click: '" + element + "'");

  // Highlight Elements before clicking
  for (int i = 0; i < 1; i++) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: black; border: 3px solid black;");
  }
}

// Called after clicking an Element
@Override
public void afterClickOn(WebElement element, WebDriver driver) {
System.out.println("Clicked Element with: '" + element + "'");
}

The following methods maintain a clear tracking system by storing both existing and updated values:

/** CHANGING VALUES | clear(), sendKeys() **/
// Before modifying values
@Override
public void beforeChangeValueOf(WebElement element, WebDriver driver) {    
  actualValue = element.getText();

  if (actualValue.isEmpty()) {
    actualValue = element.getAttribute("value");
  }
System.out.println("The existing value is: " + actualValue);
}

// After modifying values
@Override
public void afterChangeValueOf(WebElement element, WebDriver driver) {
  String modifiedValue = "";
  try {
    modifiedValue = element.getText();
  } catch (StaleElementReferenceException e) {
    System.out.println("StaleElementReferenceException is thrown");
    return;
  }

  if (modifiedValue.isEmpty()) {
    modifiedValue = element.getAttribute("value");
  }

  System.out.println("The value changed from '" + actualValue + "' to '" + modifiedValue + "'");
}

The following methods can operate before and after executing RemoteWebDriver, which is composed of both client and server. Shown here is an example with JavaScript execution:

/** JAVASCRIPT | beforeScript(), afterScript()**/
// Called before executing RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[])
@Override
public void beforeScript(String script, WebDriver driver) {
   System.out.println("JavaScript is about to execute");
}

// Called after executing RemoteWebDriver.executeScript(java.lang.String, java.lang.Object[])
@Override
public void afterScript(String script, WebDriver driver) {
  System.out.println("JavaScript is Executed");
}

The following method, which allows the user to capture screens on test failure, is one of the most important methods used in EventFiringWebDriver:

/** ON EXCEPTION | capture screenshots on test failure **/
 // Takes screenshot on any Exception thrown during test execution 
@Override
public void onException(Throwable throwable, WebDriver webdriver) {
  System.out.println("Caught Exception");
  File scrFile = ((TakesScreenshot) webdriver)
    .getScreenshotAs(OutputType.FILE);
  try {
    org.apache.commons.io.FileUtils.copyFile(scrFile, new File("C:\Testfailure.jpeg"));
  } catch (Exception e) {
    System.out.println("Unable to Save");
  }
}

Let's define a Test class to run events through the Listeners class. To do so, initialize EventFiringWebDriver along with EventListenerDriver, and finally register Listeners to the EvenFiringWebDriver instance. The following test class explicates all the EventFiringWebDriver functions on a Google web page in detail:

private WebDriver driver;
@BeforeTest
public void setUp() throws Exception {
  driver = new FirefoxDriver();
}

@Test
public void Test01() throws Exception {

  EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver);
  Listeners EL = new Listeners();
  eventDriver.register(EL);

  // beforeNavigateTo | afterNavigateTo
  eventDriver.get("http://www.bing.com");

  // beforeNavigateBack | afterNavigateBack
  eventDriver.get("http://www.google.com");
  eventDriver.navigate().back();

  // beforeNavigateForward | afterNavigateForward  
  eventDriver.navigate().forward();

  // beforeFindBy | afterFindBy  
  eventDriver.findElement(By.name("q"));

  // beforeClickOn | afterClickOn 
  eventDriver.findElement(By.id("sblsbb")).click();

  // afterScript() | beforeScript()
  JavascriptExecutor jse = (JavascriptExecutor) eventDriver;
  jse.executeScript("alert('Selenium Essentials saved my Day!')");

  // beforeChangeValueOf | afterChangeValueOf  
  eventDriver.findElement(By.name("q")).sendKeys("Selenium Essentials");

  // onException
  eventDriver.findElement(By.id("Wrong Value"));
}

@AfterTest
public void tearDown() throws Exception {
  driver.quit();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.139.8