🍏OOPS + Selenium
Object-Oriented Programming (OOPS) concepts in Selenium:
Encapsulation
public class LoginPage {
// Declare the web elements as private variables
private WebDriver driver;
private By usernameField = By.id("username");
private By passwordField = By.id("password");
private By submitButton = By.id("submit");
// Create a constructor that takes a WebDriver instance
public LoginPage(WebDriver driver) {
this.driver = driver;
}
// Provide public methods to set and get the username and password values
public void setUsername(String username) {
driver.findElement(usernameField).sendKeys(username);
}
public String getUsername() {
return driver.findElement(usernameField).getAttribute("value");
}
public void setPassword(String password) {
driver.findElement(passwordField).sendKeys(password);
}
public String getPassword() {
return driver.findElement(passwordField).getAttribute("value");
}
// Provide a public method to click on the submit button
public void clickSubmit() {
driver.findElement(submitButton).click();
}
}
//Now, we can use this page object class in our test script as follows:
public class LoginTest {
// Create a WebDriver instance
WebDriver driver = new ChromeDriver();
// Create a LoginPage instance
LoginPage loginPage = new LoginPage(driver);
// Navigate to the login page
driver.get("<https://example.com/login>");
// Set the username and password values using the page object methods
loginPage.setUsername("testuser");
loginPage.setPassword("testpass");
// Click on the submit button using the page object method
loginPage.clickSubmit();
// Verify the login result using assertions
String expectedUrl = "<https://example.com/home>";
String actualUrl = driver.getCurrentUrl();
assertEquals(expectedUrl, actualUrl, "User is not redirected to home page after login");
String expectedMessage = "Welcome, testuser!";
String actualMessage = driver.findElement(By.id("welcome-message")).getText();
assertTrue(actualMessage.contains(expectedMessage), "Welcome message is not displayed after login");
}Benefits of Encapsulation
Inheritance
Benefits of Inheritance
Polymorphism
Method Overloading (Compile Time Polymorphism)
Method Overriding (Run Time Polymorphism)
Benefits of Polymorphism in Selenium
Abstraction
Abstract Classes
Abstract Methods
Benefits of Abstract Classes and Abstract Methods
Interfaces
Implementing an Interface
Benefits of Interfaces
Last updated