Bird
Raised Fist0
Selenium Javatesting~15 mins

Page class design in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Verify login functionality using Page Object Model
Preconditions (2)
Step 1: Open browser and navigate to the login page URL
Step 2: Enter 'testuser@example.com' in the email input field
Step 3: Enter 'Test@1234' in the password input field
Step 4: Click the login button
Step 5: Wait for the dashboard page to load
✅ Expected Result: User is successfully logged in and dashboard page is displayed with URL containing '/dashboard'
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify current URL contains '/dashboard' after login
Verify login button is clickable before clicking
Verify email and password fields are displayed before entering text
Best Practices:
Use Page Object Model to separate page elements and actions
Use explicit waits to wait for elements to be visible or clickable
Use meaningful method names in page classes
Keep test logic separate from page object classes
Automated Solution
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

// Page class for Login Page
public class LoginPage {
    private WebDriver driver;
    private WebDriverWait wait;

    private By emailField = By.id("email");
    private By passwordField = By.id("password");
    private By loginButton = By.id("loginBtn");

    public LoginPage(WebDriver driver) {
        this.driver = driver;
        this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }

    public void enterEmail(String email) {
        wait.until(ExpectedConditions.visibilityOfElementLocated(emailField));
        driver.findElement(emailField).clear();
        driver.findElement(emailField).sendKeys(email);
    }

    public void enterPassword(String password) {
        wait.until(ExpectedConditions.visibilityOfElementLocated(passwordField));
        driver.findElement(passwordField).clear();
        driver.findElement(passwordField).sendKeys(password);
    }

    public void clickLogin() {
        wait.until(ExpectedConditions.elementToBeClickable(loginButton));
        driver.findElement(loginButton).click();
    }
}

// Test class
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class LoginTest {
    private WebDriver driver;
    private LoginPage loginPage;

    @BeforeClass
    public void setUp() {
        // Set path to chromedriver executable if needed
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://example.com/login");
        loginPage = new LoginPage(driver);
    }

    @Test
    public void testValidLogin() {
        loginPage.enterEmail("testuser@example.com");
        loginPage.enterPassword("Test@1234");
        loginPage.clickLogin();

        // Wait for URL to contain /dashboard
        new org.openqa.selenium.support.ui.WebDriverWait(driver, Duration.ofSeconds(10))
            .until(d -> d.getCurrentUrl().contains("/dashboard"));

        Assert.assertTrue(driver.getCurrentUrl().contains("/dashboard"), "Dashboard page should be displayed after login");
    }

    @AfterClass
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

The LoginPage class encapsulates the login page elements and actions. It uses By locators with IDs, which are stable and fast. The constructor initializes the WebDriver and WebDriverWait for explicit waits.

Each method waits explicitly for the element to be visible or clickable before interacting. This avoids flaky tests due to timing issues.

The LoginTest class sets up the browser, navigates to the login page, and uses the page object methods to perform login steps. It then waits for the URL to contain '/dashboard' and asserts this condition to verify successful login.

Finally, the browser is closed in @AfterClass to clean up resources.

This design keeps page details separate from test logic, making tests easier to maintain and read.

Common Mistakes - 3 Pitfalls
Using Thread.sleep() instead of explicit waits
Locating elements inside test methods instead of page classes
Using brittle locators like absolute XPath
Bonus Challenge

Now add data-driven testing with 3 different sets of login credentials (valid and invalid) to verify login behavior.

Show Hint

Practice

(1/5)
1. What is the main purpose of a page class in Selenium Java?
easy
A. To handle API requests
B. To write test assertions directly
C. To group web page elements and actions in one place
D. To manage database connections

Solution

  1. Step 1: Understand the role of page classes

    Page classes organize locators and actions related to a specific web page.
  2. Step 2: Identify the main purpose

    This organization improves code readability and reuse by keeping page details in one place.
  3. Final Answer:

    To group web page elements and actions in one place -> Option C
  4. Quick Check:

    Page class purpose = Group elements and actions [OK]
Hint: Page classes group elements and actions per page [OK]
Common Mistakes:
  • Confusing page classes with test classes
  • Using page classes for database or API logic
  • Writing assertions inside page classes
2. Which of the following is the correct way to declare a locator in a Selenium page class using Java?
easy
A. public void submitButton = driver.findElement(By.id("submit"));
B. public String submitButton = "submit";
C. private WebElement submitButton = driver.findElement(By.id("submit"));
D. private By submitButton = By.id("submit");

Solution

  1. Step 1: Recall best practice for locators

    Locators should be stored as By objects, not WebElement, to delay element lookup.
  2. Step 2: Check each option

    private By submitButton = By.id("submit"); correctly declares a private By locator with By.id("submit").
  3. Final Answer:

    private By submitButton = By.id("submit"); -> Option D
  4. Quick Check:

    Locators = By objects [OK]
Hint: Use By for locators, not WebElement directly [OK]
Common Mistakes:
  • Declaring locators as WebElement fields
  • Using public visibility for locators
  • Assigning void type to variables
3. Given the following page class snippet, what will loginPage.getTitle() return if the page title is "Welcome Page"?
public class LoginPage {
  private WebDriver driver;
  public LoginPage(WebDriver driver) {
    this.driver = driver;
  }
  public String getTitle() {
    return driver.getTitle();
  }
}
medium
A. "Welcome Page"
B. "Login Page"
C. null
D. Throws NullPointerException

Solution

  1. Step 1: Understand getTitle() method

    The method calls driver.getTitle(), which returns the current page title.
  2. Step 2: Match with given page title

    The page title is "Welcome Page", so getTitle() returns this string.
  3. Final Answer:

    "Welcome Page" -> Option A
  4. Quick Check:

    driver.getTitle() = "Welcome Page" [OK]
Hint: driver.getTitle() returns current page title string [OK]
Common Mistakes:
  • Assuming getTitle() returns page class name
  • Expecting null if not set explicitly
  • Confusing with element text retrieval
4. Identify the error in this page class method:
public void clickLogin() {
  WebElement loginBtn = driver.findElement(By.id("login"));
  loginBtn.click();
}
medium
A. No error, method is correct
B. Should store locator as a By field, not find element inside method
C. Missing exception handling for element not found
D. Method should return WebElement instead of void

Solution

  1. Step 1: Review locator usage best practice

    Locators should be stored as By fields in the page class, not found inside methods.
  2. Step 2: Identify the problem

    Finding element inside method reduces reuse and violates page class design principles.
  3. Final Answer:

    Should store locator as a By field, not find element inside method -> Option B
  4. Quick Check:

    Locators as By fields = best practice [OK]
Hint: Keep locators as fields, find elements in methods [OK]
Common Mistakes:
  • Finding elements repeatedly inside methods
  • Ignoring locator reuse
  • Assuming exception handling is mandatory here
5. You want to design a page class for a login page with username, password fields, and a login button. Which design approach is best to follow?
hard
A. Store locators as private By fields; create public methods to enter username, enter password, and click login
B. Store WebElement fields publicly and access them directly in tests
C. Write all test steps inside the page class constructor
D. Use static methods only without storing any locators

Solution

  1. Step 1: Recall page class design principles

    Locators should be private By fields; actions should be public methods for reuse and encapsulation.
  2. Step 2: Evaluate options

    Store locators as private By fields; create public methods to enter username, enter password, and click login follows best practice by separating locators and actions clearly.
  3. Final Answer:

    Store locators as private By fields; create public methods to enter username, enter password, and click login -> Option A
  4. Quick Check:

    Private locators + public methods = best design [OK]
Hint: Private locators + public action methods = good page class [OK]
Common Mistakes:
  • Making locators public and exposing WebElements
  • Putting test logic in constructors
  • Using static methods without instance context
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard