You are on page 1of 1

Chapter 4

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
ff The Checking an element's status recipe

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"));

95

You might also like