Checking an element's presence

The Selenium WebDriver does not implement Selenium RC's isElementPresent() method to check if an element is present on a page. This method is useful for building a reliable test that checks an element's presence before performing any action on it.

In this recipe, we will write a method similar to the isElementPresent() method.

How to do it...

To implement the isElementPresent() method, follow these steps:

  1. Create a method isElementPresent() and keep it accessible to your tests, shown as follows:
    private boolean isElementPresent(By by) {
      try {
        driver.findElement(by);
          return true;
        } catch (NoSuchElementException e) {
          return false;
      }
    }
  2. Now, implement a test that calls the isElementPresent() method. It will check if the desired element is present on a page. If found, it will click on the element; else it fails the test. This is done as follows:
    @Test
    public void testIsElementPresent() {
      // Check if element with locator criteria exists on Page
      if (isElementPresent(By.name("airbags"))) {
        // Get the checkbox and select it
        WebElement airbag = driver.findElement(By.name("airbags"));
        if (!airbag.isSelected()) {
          airbag.click();
        }
      } else {
        fail("Airbag Checkbox doesn't exists!!");
      }
    }

How it works...

The isElementPresent() method takes a locator using an instance of By. It then calls the findElement() method. If the element is not found, a NoSuchElementException exception will be thrown. Using the try and catch block, the isElementPresent() method will return true if the element is found and no exception is thrown; otherwise, it will return false if NoSuchElementException is thrown by the findElement() method.

See also

  • The Checking an element's status recipe
..................Content has been hidden....................

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