Bird
Raised Fist0
Selenium Javatesting~15 mins

Action methods per page in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Login functionality using action methods in Page Object
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com/login'
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: Verify that the user is redirected to the dashboard page with URL containing '/dashboard'
✅ Expected Result: User is successfully logged in and dashboard page is displayed
Automation Requirements - Selenium WebDriver with Java and TestNG
Assertions Needed:
Verify email input field accepts the correct text
Verify password input field accepts the correct text
Verify login button is clickable
Verify current URL contains '/dashboard' after login
Best Practices:
Use Page Object Model to separate page actions and locators
Create action methods for each user interaction in the page class
Use explicit waits to wait for elements to be interactable
Use TestNG assertions for validation
Keep test method clean by calling page action methods
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 org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;

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

    private By emailInput = By.id("email");
    private By passwordInput = By.id("password");
    private By loginButton = By.id("loginBtn");

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

    // Action method to enter email
    public void enterEmail(String email) {
        WebElement emailField = wait.until(ExpectedConditions.elementToBeClickable(emailInput));
        emailField.clear();
        emailField.sendKeys(email);
    }

    // Action method to enter password
    public void enterPassword(String password) {
        WebElement passwordField = wait.until(ExpectedConditions.elementToBeClickable(passwordInput));
        passwordField.clear();
        passwordField.sendKeys(password);
    }

    // Action method to click login button
    public void clickLogin() {
        WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(loginButton));
        loginBtn.click();
    }
}

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

    @BeforeClass
    public void setUp() {
        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'
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        boolean urlContainsDashboard = wait.until(ExpectedConditions.urlContains("/dashboard"));

        Assert.assertTrue(urlContainsDashboard, "URL should contain '/dashboard' after login");
    }

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

This code uses the Page Object Model to separate the login page actions from the test logic.

The LoginPage class has action methods: enterEmail, enterPassword, and clickLogin. Each method waits explicitly for the element to be clickable before interacting, improving reliability.

The test class LoginTest initializes the browser and page object in @BeforeClass. The test method calls the action methods to perform login steps clearly and asserts the URL contains '/dashboard' after login.

Finally, @AfterClass closes the browser to clean up.

This structure keeps the test clean and easy to maintain, following best practices.

Common Mistakes - 4 Pitfalls
Directly locating elements and interacting in the test method instead of using page action methods
Using Thread.sleep() instead of explicit waits
Not clearing input fields before sending keys
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 action methods in a Selenium page object?
easy
A. To represent user actions like clicking or typing on the page
B. To store test data for validation
C. To configure browser settings
D. To generate test reports automatically

Solution

  1. Step 1: Understand the role of action methods

    Action methods are designed to perform user interactions such as clicking buttons or entering text.
  2. Step 2: Differentiate from other page object responsibilities

    Storing data, configuring browsers, or generating reports are not the role of action methods.
  3. Final Answer:

    To represent user actions like clicking or typing on the page -> Option A
  4. Quick Check:

    Action methods = user actions [OK]
Hint: Action methods do what a user does on the page [OK]
Common Mistakes:
  • Confusing action methods with data storage
  • Thinking action methods configure the browser
  • Assuming action methods generate reports
2. Which of the following is the correct way to define an action method that clicks a button using Selenium Java?
easy
A. public void clickButton() { driver.findElement(By.id("btn")).getText(); }
B. public void clickButton() { driver.findElement(By.id("btn")).click(); }
C. public void clickButton() { driver.findElement(By.id("btn")).sendKeys(); }
D. public void clickButton() { driver.findElement(By.id("btn")).clear(); }

Solution

  1. Step 1: Identify the correct Selenium method for clicking

    The method click() performs a click action on the element.
  2. Step 2: Check the other methods

    sendKeys() types text, getText() reads text, and clear() clears input fields.
  3. Final Answer:

    public void clickButton() { driver.findElement(By.id("btn")).click(); } -> Option B
  4. Quick Check:

    Click action uses click() method [OK]
Hint: Click uses click(), not sendKeys() or getText() [OK]
Common Mistakes:
  • Using sendKeys() instead of click() to click
  • Calling getText() which only reads text
  • Using clear() which clears input fields
3. Given the following action method in a page object:
public void enterUsername(String name) {
    driver.findElement(By.name("username")).sendKeys(name);
}

What will happen when enterUsername("testUser") is called?
medium
A. The text "testUser" will be typed into the username input field
B. The username input field will be cleared
C. An error will occur because sendKeys requires no arguments
D. The username input field will be clicked but not typed

Solution

  1. Step 1: Understand sendKeys() usage

    The sendKeys() method types the given string into the located input field.
  2. Step 2: Analyze the method call

    Calling enterUsername("testUser") passes "testUser" to sendKeys(), so it types this text.
  3. Final Answer:

    The text "testUser" will be typed into the username input field -> Option A
  4. Quick Check:

    sendKeys("text") types text [OK]
Hint: sendKeys(text) types text into input fields [OK]
Common Mistakes:
  • Thinking sendKeys() clears the field
  • Believing sendKeys() takes no arguments
  • Confusing click() with sendKeys()
4. Consider this action method:
public void submitForm() {
    driver.findElement(By.id("submitBtn")).click();
    driver.findElement(By.id("submitBtn")).click();
}

What is the issue with this method?
medium
A. It does not locate the submit button correctly
B. It uses an invalid locator syntax
C. It will cause a compilation error due to duplicate lines
D. It clicks the submit button twice unnecessarily

Solution

  1. Step 1: Review the method actions

    The method calls click() on the same button twice in a row.
  2. Step 2: Understand the impact

    Clicking twice may cause unexpected behavior or duplicate submissions.
  3. Final Answer:

    It clicks the submit button twice unnecessarily -> Option D
  4. Quick Check:

    Duplicate clicks cause redundant actions [OK]
Hint: Avoid repeating click() on same element twice [OK]
Common Mistakes:
  • Thinking duplicate lines cause compile errors
  • Assuming locator syntax is wrong
  • Believing the button is not found
5. You want to create an action method that selects a checkbox only if it is not already selected. Which of the following is the best implementation?
hard
A. public void selectCheckbox() { WebElement checkbox = driver.findElement(By.id("agree")); checkbox.isSelected(); }
B. public void selectCheckbox() { driver.findElement(By.id("agree")).click(); }
C. public void selectCheckbox() { WebElement checkbox = driver.findElement(By.id("agree")); if (!checkbox.isSelected()) { checkbox.click(); } }
D. public void selectCheckbox() { WebElement checkbox = driver.findElement(By.id("agree")); checkbox.clear(); }

Solution

  1. Step 1: Check if checkbox is already selected

    Use isSelected() to verify checkbox state before clicking.
  2. Step 2: Click only if not selected

    Clicking only when unchecked prevents unchecking it accidentally.
  3. Final Answer:

    public void selectCheckbox() { WebElement checkbox = driver.findElement(By.id("agree")); if (!checkbox.isSelected()) { checkbox.click(); } } -> Option C
  4. Quick Check:

    Check isSelected() before click to avoid toggling [OK]
Hint: Click checkbox only if not selected using isSelected() [OK]
Common Mistakes:
  • Clicking checkbox without checking state
  • Calling isSelected() without action
  • Using clear() on checkbox which is invalid
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