@Findby annotation in Selenium Java

The @FindBy annotation is a part of the Page Object Model (POM) in Selenium with Java. It is used to locate and declare WebElement variables in a page class, making the code cleaner and more maintainable. This annotation helps in keeping the locators centralized and separated from the test logic.

Here’s how you can use @FindBy in Java Selenium:

  1. Import Necessary Packages:
  2. Make sure to import the required packages at the beginning of your Java file:
import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; 
  1. Using @FindBy with WebElement:
  2. Declare WebElement variables and annotate them with @FindBy along with the locator strategy. For example:
public class LoginPage { @FindBy(id = "username") private WebElement usernameInput; @FindBy(id = "password") private WebElement passwordInput; @FindBy(xpath = "//button[@id='loginButton']") private WebElement loginButton; } 
  1. In this example:
  • @FindBy(id = "username"): Locates the element with the id “username” and assigns it to the usernameInput variable.
  • @FindBy(id = "password"): Locates the element with the id “password” and assigns it to the passwordInput variable.
  • @FindBy(xpath = "//button[@id='loginButton']"): Locates the button element with the specified XPath and assigns it to the loginButton variable.
  1. Initializing PageFactory:
  2. In the page class constructor or an initialization method, use PageFactory.initElements to initialize the @FindBy-annotated WebElements:
import org.openqa.selenium.support.PageFactory; public class LoginPage { // Existing code public LoginPage(WebDriver driver) { PageFactory.initElements(driver, this); } } 
  1. This step is crucial for the @FindBy annotations to work, as it initializes the WebElements with the appropriate locators.
  2. Usage in Test Classes:
  3. Now you can use these WebElements in your test classes without worrying about the specific locators:
public class LoginTest { @Test public void loginTest() { WebDriver driver = new ChromeDriver(); LoginPage loginPage = new LoginPage(driver); loginPage.usernameInput.sendKeys("yourUsername"); loginPage.passwordInput.sendKeys("yourPassword"); loginPage.loginButton.click(); // Rest of your test logic } } 

By using @FindBy, you create a clean separation between the page structure and the test logic, improving code readability and maintainability.

Leave a comment

Your email address will not be published. Required fields are marked *