0
0
Selenium Javatesting~5 mins

Action chain execution (perform) in Selenium Java

Choose your learning style9 modes available
Introduction

Action chains let you do several mouse or keyboard steps in order, like clicking and dragging. You use perform() to actually run these steps.

You want to hover over a menu to see a dropdown.
You need to drag and drop an item on a webpage.
You want to right-click on an element to open a context menu.
You want to type keys with pauses or special keys like SHIFT.
You want to combine multiple actions like click, hold, move, and release.
Syntax
Selenium Java
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();

perform() runs all the actions you added in order.

You must call perform() at the end to execute the chain.

Examples
This moves the mouse over the menu element to trigger hover effects.
Selenium Java
Actions actions = new Actions(driver);
actions.moveToElement(menu).perform();
This drags an element from source to target and releases it.
Selenium Java
Actions actions = new Actions(driver);
actions.clickAndHold(source).moveToElement(target).release().perform();
This right-clicks on the element to open the context menu.
Selenium Java
Actions actions = new Actions(driver);
actions.contextClick(element).perform();
Sample Program

This test opens a webpage, finds a menu element, moves the mouse over it using an action chain, and prints a success message.

Selenium Java
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.interactions.Actions;

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

            Actions actions = new Actions(driver);
            actions.moveToElement(menu).perform();

            System.out.println("Hover action performed successfully.");
        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Always call perform() to run the actions; without it, nothing happens.

Chain multiple actions before perform() to do complex steps smoothly.

Use explicit waits if elements appear after hover or other actions.

Summary

Action chains let you combine mouse and keyboard steps.

perform() runs all the steps you added.

Use action chains for hover, drag-drop, right-click, and more.