@FindBy annotations help you find web elements on a page easily without writing long code. They make your test code cleaner and easier to read.
@FindBy annotations in Selenium Java
@FindBy(how = How.ID, using = "elementId")
private WebElement elementName;You can use different locator types like id, name, xpath, css, etc.
The annotation is placed above the WebElement variable declaration.
@FindBy(id = "submitBtn")
private WebElement submitButton;@FindBy(name = "username")
private WebElement usernameField;@FindBy(xpath = "//div[@class='alert']")
private WebElement alertMessage;@FindBy(css = ".nav-menu > li:nth-child(2)")
private WebElement secondMenuItem;This example shows a simple login page class using @FindBy annotations to locate username, password, and login button elements. The test class opens the browser, navigates to the login page, and performs a login.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class LoginPage { @FindBy(id = "username") private WebElement usernameInput; @FindBy(id = "password") private WebElement passwordInput; @FindBy(id = "loginBtn") private WebElement loginButton; public LoginPage(WebDriver driver) { PageFactory.initElements(driver, this); } public void login(String user, String pass) { usernameInput.sendKeys(user); passwordInput.sendKeys(pass); loginButton.click(); } } // Test class example import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class LoginTest { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://example.com/login"); LoginPage loginPage = new LoginPage(driver); loginPage.login("testuser", "testpass"); System.out.println("Login attempted"); driver.quit(); } }
Always initialize elements with PageFactory.initElements() in the constructor.
Use meaningful variable names for WebElements to keep code readable.
Prefer specific locators like id or name over complex XPath for better speed and reliability.
@FindBy annotations simplify locating web elements in Selenium tests.
They help keep test code clean and organized, especially with Page Object Model.
Remember to initialize elements with PageFactory before using them.
Practice
@FindBy annotation in Selenium Java?Solution
Step 1: Understand the role of
The@FindBy@FindByannotation is used to specify how to find a web element on a page, such as by id, name, xpath, etc.Step 2: Compare with other options
Options B, C, and D describe other Selenium features but not element locating.Final Answer:
To locate web elements on a page using different strategies -> Option BQuick Check:
@FindBy locates elements = A [OK]
- Confusing @FindBy with WebDriver commands
- Thinking @FindBy executes scripts
- Assuming @FindBy starts browser sessions
@FindBy annotation?Solution
Step 1: Check correct attribute usage
The@FindByannotation requires the attribute name and value as a string. For ID, it isid = "value".Step 2: Validate each option
@FindBy(id = "submitBtn") correctly usesid = "submitBtn". @FindBy(name = submitBtn) misses quotes. @FindBy(xpath = submitBtn) uses xpath but without quotes. @FindBy(css = #submitBtn) uses CSS selector but with incorrect syntax (should becss = "#submitBtn").Final Answer:
@FindBy(id = "submitBtn") -> Option AQuick Check:
Correct syntax uses id with quotes = B [OK]
- Omitting quotes around locator values
- Mixing locator types incorrectly
- Using invalid syntax for CSS selectors
button.isDisplayed() is called?public class LoginPage {
@FindBy(name = "loginBtn")
WebElement button;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
}
// In test method:
LoginPage page = new LoginPage(driver);
boolean visible = page.button.isDisplayed();
System.out.println(visible);Solution
Step 1: Understand PageFactory initialization
The constructor callsPageFactory.initElements(driver, this), which initializes all @FindBy annotated elements, includingbutton.Step 2: Check behavior of
If the element with name 'loginBtn' exists and is visible,isDisplayed()isDisplayed()returns true; otherwise false. No NullPointerException occurs because initialization is done.Final Answer:
true if the element with name 'loginBtn' is visible on the page -> Option CQuick Check:
PageFactory initializes elements = true if visible [OK]
- Assuming elements are null without initialization
- Confusing isDisplayed() with element presence
- Ignoring the need to call PageFactory.initElements
@FindBy:public class HomePage {
@FindBy(xpath = "//button[@id='start']")
WebElement startButton;
public HomePage(WebDriver driver) {
// Missing initialization
}
}Solution
Step 1: Check element initialization
The constructor does not callPageFactory.initElements(driver, this), sostartButtonremains null.Step 2: Validate other options
XPath syntax is correct. WebElement visibility (private/public) is optional. Manual initialization is not needed if PageFactory is used.Final Answer:
Missing call to PageFactory.initElements to initialize elements -> Option AQuick Check:
PageFactory.initElements missing = D [OK]
- Forgetting to initialize elements with PageFactory
- Assuming XPath syntax errors without checking
- Thinking manual findElement is required with @FindBy
@FindBy. Which declaration is correct to store all matching elements in a list?public class ProductsPage {
// Which line is correct?
}Solution
Step 1: Understand locating multiple elements
To store multiple elements, the field must be aList<WebElement>. Using@FindBywithclassNamelocator is valid.Step 2: Check each option's type and locator
@FindBy(className = "product-item") List<WebElement> products; usesList<WebElement>with correct locator. Options A, B, and D use singleWebElement, which can only hold one element.Final Answer:
@FindBy(className = "product-item") List<WebElement> products; -> Option DQuick Check:
Multiple elements need List<WebElement> = C [OK]
- Declaring multiple elements as single WebElement
- Using wrong locator type for multiple elements
- Forgetting to import java.util.List
Ready to prove it?
Pass the test and this pattern moves unknown
