</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

What is the use of @FindBy annotation in TestNG/Selenium?

@FindBy is a PageFactory annotation used to locate WebElements in the Page Object Model, replacing driver.findElement() calls with cleaner field declarations.

Answer

@FindBy Annotation in Selenium

@FindBy is an annotation from Selenium''s PageFactory class used in the Page Object Model (POM) to identify and initialize web elements.

Basic usage:

Java
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {

    @FindBy(id = "username")
    WebElement usernameField;

    @FindBy(name = "password")
    WebElement passwordField;

    @FindBy(xpath = "//button[@type='submit']")
    WebElement loginButton;

    @FindBy(css = ".error-message")
    WebElement errorMessage;

    public LoginPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
        // @FindBy elements are initialized here
    }

    public void login(String user, String pass) {
        usernameField.sendKeys(user);
        passwordField.sendKeys(pass);
        loginButton.click();
    }
}

Supported locator strategies:

Java
@FindBy(id = "elementId")
@FindBy(name = "elementName")
@FindBy(className = "css-class")
@FindBy(tagName = "input")
@FindBy(linkText = "Click Here")
@FindBy(partialLinkText = "Click")
@FindBy(css = "div.container > input")
@FindBy(xpath = "//div[@class='content']")

Multiple locators with @FindBys (AND logic):

Java
// Finds element with id="search" AND class="active"
@FindBys({
    @FindBy(id = "search"),
    @FindBy(className = "active")
})
WebElement searchBox;

Multiple locators with @FindAll (OR logic):

Java
// Finds all elements matching EITHER locator
@FindAll({
    @FindBy(id = "btn1"),
    @FindBy(className = "submit-btn")
})
List<WebElement> buttons;

@FindBy vs driver.findElement():

Feature@FindBy (PageFactory)driver.findElement()
Code readabilityCleaner, declarativeVerbose, inline
Element cachingLazy (found when used)Immediate
POM integrationStandard approachUsed anywhere
StaleElement riskHigher (cached)Lower (re-found each time)

Key point: @FindBy is used to identify elements in the Page Factory approach to POM. Elements are initialized by calling PageFactory.initElements(driver, this) in the page constructor.

Follow AutomateQA

Related Topics