0
0
Selenium Javatesting~5 mins

Click actions in Selenium Java

Choose your learning style9 modes available
Introduction

Click actions let you simulate a mouse click on a webpage element. This helps test if buttons, links, or other clickable parts work correctly.

When you want to test if a button submits a form.
When you need to check if clicking a link opens the right page.
When verifying if clicking a checkbox selects it.
When testing if clicking a menu item opens a submenu.
When automating user steps that require clicking elements.
Syntax
Selenium Java
WebElement element = driver.findElement(By.id("value"));
element.click();

Use a clear locator to find the element before clicking.

Make sure the element is visible and enabled before clicking.

Examples
Clicks a button with the id 'submitBtn'.
Selenium Java
driver.findElement(By.id("submitBtn")).click();
Finds a link with text 'Home' and clicks it.
Selenium Java
WebElement link = driver.findElement(By.linkText("Home"));
link.click();
Clicks the first element with class 'menu-item'.
Selenium Java
driver.findElement(By.cssSelector(".menu-item")).click();
Sample Program

This test opens a login page, enters username and password, clicks the login button, and checks if the page title changes to 'Dashboard' to confirm success.

Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ClickActionTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/login");
            WebElement username = driver.findElement(By.id("username"));
            WebElement password = driver.findElement(By.id("password"));
            WebElement loginButton = driver.findElement(By.id("loginBtn"));

            username.sendKeys("testuser");
            password.sendKeys("password123");
            loginButton.click();

            // Check if login was successful by checking page title
            String title = driver.getTitle();
            if (title.equals("Dashboard")) {
                System.out.println("Test Passed: Login successful.");
            } else {
                System.out.println("Test Failed: Login unsuccessful.");
            }
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Always wait for elements to be visible before clicking to avoid errors.

Use explicit waits if the page loads slowly.

Clicking hidden or disabled elements will cause exceptions.

Summary

Click actions simulate user clicks on web elements.

Find the element first, then call click().

Ensure elements are visible and enabled before clicking.