Checking an element's state

Many a time a test fails to click on an element or enter text in a field, as the element is disabled or exists in the DOM but is hidden on the page. This will result in an error being thrown and the test resulting in failure. To build reliable tests that can run unattended, a robust exception and error handling is needed in the test flow.

We can handle these problems by checking the state of elements. The WebElement interface provides the following methods to check the state of an element:

Method

Purpose

isEnabled()

This method checks if an element is enabled. It returns true if enabled, else false if disabled.

isSelected()

This method checks if an element is selected (radio button, checkbox, and so on). It returns true if selected, else false if deselected.

isDisplayed()

This method checks if an element is displayed.

In this recipe, we will use some of these methods to check the status and handle possible errors.

How to do it...

We will create a test where a checkbox for the LED headlamp option needs to be selected on a page. This checkbox will be enabled or disabled based on the previously selected option. Before selecting this checkbox, we will make sure that it's enabled for selection, as follows:

@Test
public void testElementIsEnabled() {
  // Get the Checkbox as WebElement using it's name attribute
  WebElement ledheadlamp = driver.findElement(By.name("ledheadlamp"));

  // Check if its enabled before selecting it
  if (ledheadlamp.isEnabled()) {
    // Check if its already selected? otherwise select the Checkbox
    if (!ledheadlamp.isSelected()) {
      ledheadlamp.click();
    }
  } else {
    fail("LED Lamp Checkbox is disabled!!");
  }
}

How it works...

We are selecting a checkbox by checking the two states of an element—first, it is enabled, and second, it is not selected. We can use the isEnabled() function of the WebElement interface, which returns true if the element is enabled or false if it's disabled. The test will fail if the checkbox is disabled. If we do not check this condition, the test will possibly throw an exception saying the object is disabled, as follows:

// Check if its enabled before selecting it
if (ledheadlamp.isEnabled()) {
  // Check if its already selected? otherwise select the Checkbox
  if (!ledheadlamp.isSelected()) {
    ledheadlamp.click();
  }
} else {
  fail("LED Lamp Checkbox is disabled!!");
}
..................Content has been hidden....................

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