Page Object Model (POM) is a design pattern in Selenium WebDriver that helps in enhancing test maintenance and scalability by abstracting web elements and actions on a web page into reusable classes called Page Objects.
Benefits of using POM:
In this example, we'll separate the WebElement locators into a separate class and use @FindBy annotations for clarity and maintainability.
LoginPageElements.java
class LoginPageElements { WebDriver driver; @FindBy(id = "username") WebElement usernameField; @FindBy(id = "password") WebElement passwordField; @FindBy(id = "loginButton") WebElement loginButton; public LoginPageElements(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } }
LoginPage.java:
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 { private WebDriver driver; private LoginPageElements elements; public LoginPage(WebDriver driver) { this.driver = driver; this.elements = new LoginPageElements(driver); PageFactory.initElements(driver, this); } public void enterUsername(String username) { elements.usernameField.sendKeys(username); } public void enterPassword(String password) { elements.passwordField.sendKeys(password); } public void clickLoginButton() { elements.loginButton.click(); } }
Explanation:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3