0
0
Selenium Javatesting~15 mins

Test class consuming page objects in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify login functionality using page objects
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com/login'
Step 2: Enter 'testuser' in the username 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 redirected to the dashboard page with URL containing '/dashboard' and a welcome message is displayed
Automation Requirements - Selenium WebDriver with JUnit 5
Assertions Needed:
Verify current URL contains '/dashboard'
Verify welcome message element is displayed and contains text 'Welcome, testuser'
Best Practices:
Use Page Object Model to separate page interactions
Use explicit waits to wait for elements
Use meaningful and stable locators (id, name, or CSS selectors)
Use JUnit 5 assertions
Close browser after test
Automated Solution
Selenium Java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;

import static org.junit.jupiter.api.Assertions.*;

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

    private By usernameInput = By.id("username");
    private By passwordInput = By.id("password");
    private By loginButton = By.cssSelector("button[type='submit']");

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

    public void enterUsername(String username) {
        WebElement userField = wait.until(ExpectedConditions.visibilityOfElementLocated(usernameInput));
        userField.clear();
        userField.sendKeys(username);
    }

    public void enterPassword(String password) {
        WebElement passField = wait.until(ExpectedConditions.visibilityOfElementLocated(passwordInput));
        passField.clear();
        passField.sendKeys(password);
    }

    public void clickLogin() {
        WebElement button = wait.until(ExpectedConditions.elementToBeClickable(loginButton));
        button.click();
    }

    public void loginAs(String username, String password) {
        enterUsername(username);
        enterPassword(password);
        clickLogin();
    }
}

// Page Object for Dashboard Page
class DashboardPage {
    private WebDriver driver;
    private WebDriverWait wait;

    private By welcomeMessage = By.id("welcome-msg");

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

    public boolean isWelcomeMessageDisplayed() {
        return wait.until(ExpectedConditions.visibilityOfElementLocated(welcomeMessage)).isDisplayed();
    }

    public String getWelcomeMessageText() {
        return driver.findElement(welcomeMessage).getText();
    }
}

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

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://example.com/login");
        loginPage = new LoginPage(driver);
        dashboardPage = new DashboardPage(driver);
    }

    @Test
    public void testValidLogin() {
        loginPage.loginAs("testuser", "Test@1234");

        // Wait for URL to contain '/dashboard'
        new WebDriverWait(driver, Duration.ofSeconds(10))
                .until(ExpectedConditions.urlContains("/dashboard"));

        assertTrue(driver.getCurrentUrl().contains("/dashboard"), "URL should contain '/dashboard'");
        assertTrue(dashboardPage.isWelcomeMessageDisplayed(), "Welcome message should be displayed");
        assertEquals("Welcome, testuser", dashboardPage.getWelcomeMessageText(), "Welcome message text should match");
    }

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

The code uses the Page Object Model to separate page interactions from the test logic.

LoginPage class handles entering username, password, and clicking login with explicit waits to ensure elements are ready.

DashboardPage class checks for the welcome message presence and text.

The LoginTest class sets up the ChromeDriver, opens the login page, uses the page objects to perform login, then asserts the URL and welcome message.

Explicit waits ensure the test waits for the page to load and elements to appear before interacting or asserting.

Finally, the browser is closed in the tearDown method to clean up.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() instead of explicit waits
Locating elements directly in the test class instead of using page objects
Using brittle locators like absolute XPath
Not closing the browser after tests
Bonus Challenge

Now add data-driven testing with 3 different sets of login credentials (valid and invalid) using JUnit 5 parameterized tests.

Show Hint