Site icon TestingDocs.com

Page Object @FindBy Annotation

Overview

While writing tests, we can mark the elements in Page Object with @FindBy annotation. Also, it is used by web driver to locate the element on the web page. Also, it is used to mark a field on a Page Object to indicate an alternative mechanism for locating the element or a list of elements.

Furthermore, you can use the annotation in conjunction with PageFactory, this allows you to quickly and easily create PageObjects.

 

There are different ways of using @FindBy annotation.

@FindBy(how = How.HowValues, using ="value")
WebElement webElementName;
or

@FindBy(locating_mechanism ="value")
WebElement webElementName;

 

Here, ‘How’ is an enum that can have one of the following values: CLASS_NAME,  CSS,  ID,  ID_OR_NAME,  LINK_TEXT,  NAME,  PARTIAL_LINK_TEXT,  TAG_NAME,  XPATH.
Also, the “value” is an expression that defines a selector of the ‘how’ type.

 

You can either use this annotation by specifying both “how” and “using” or by specifying one of the location strategies (eg: “id”) with an appropriate value to use. Also, both options will delegate down to the matching By methods in By class.

Both these two annotations point to the same element:
@FindBy(id = “emailID”)
WebElement emailAddress;

@FindBy(how = How.ID, using = “emailID”)
WebElement emailAddress;

One best practice is to declare elements using private attribute. Therefore, it will not be accessible from within an outside class. Furthermore, to access the value of the webElement from an outside class, you will need to declare a getter method.

@FindBy(how = How.ID, using = "emailID")
private WebElement emailAddress;
public WebElement getEmailAddress() {
return emailAddress;
}

 

Multiple WebElements

You can also obtain a list of webElements, if the selector you use to declare the webElement returns more than one results. Therefore, in this case, you will define the list of webElements as follows:

@FindBy(how = How.HowValues, using = "value")

private List<WebElement> collectionOfElements;
The getter to return a list instead of a webElement, as follows:

public List<WebElement> getCollectionOfElements() {
        return collectionOfElements;
}

 

In conclusion, once the driver gets the page, all the elements declared by findby annotation are declared by the respective locating mechanism used in the annotation.

Selenium Tutorials on this website:

https://www.testingdocs.com/selenium-webdriver-tutorial/

Official Website:

https://www.selenium.dev/

Exit mobile version