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:
- Import Necessary Packages:
- 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;
- Using
@FindBywith WebElement: - Declare
WebElementvariables and annotate them with@FindByalong 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; }
- In this example:
@FindBy(id = "username"): Locates the element with the id “username” and assigns it to theusernameInputvariable.@FindBy(id = "password"): Locates the element with the id “password” and assigns it to thepasswordInputvariable.@FindBy(xpath = "//button[@id='loginButton']"): Locates the button element with the specified XPath and assigns it to theloginButtonvariable.
- Initializing PageFactory:
- In the page class constructor or an initialization method, use
PageFactory.initElementsto initialize the@FindBy-annotated WebElements:
import org.openqa.selenium.support.PageFactory; public class LoginPage { // Existing code public LoginPage(WebDriver driver) { PageFactory.initElements(driver, this); } }
- This step is crucial for the
@FindByannotations to work, as it initializes the WebElements with the appropriate locators. - Usage in Test Classes:
- 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.