Actions Class in Selenium

 

In Selenium WebDriver (Java), the Actions class is used to handle complex user interactions and advanced gestures like mouse movements, key presses, drag-and-drop, right-clicks, double-clicks, etc.


Why Use Actions Class?

  • Simulate mouse and keyboard actions

  • Handle advanced interactions not possible with simple WebElement methods


Import Statement:

import org.openqa.selenium.interactions.Actions;


Creating an Actions Object:

Actions actions = new Actions(driver);
Where driver is your instance of WebDriver.


Common Methods of Actions Class:

MethodDescription
click()Clicks at the current mouse location
click(WebElement)Clicks on a given element
doubleClick() / doubleClick(element)Double-clicks
contextClick() / contextClick(element)Right-clicks
moveToElement(element)Moves mouse to element
dragAndDrop(source, target)Drags source to target
clickAndHold() / release()Click and hold / release
sendKeys(Keys.XXX)Sends keyboard keys


Most of these methods are chained and must be followed by .perform() to execute.


Example Code Snippets:

1. Mouse Hover

WebElement element = driver.findElement(By.id("menu"));
Actions actions = new Actions(driver);
actions.moveToElement(element).perform();

2. Right Click (Context Click)

WebElement element = driver.findElement(By.id("rightClickBtn"));
Actions actions = new Actions(driver);
actions.contextClick(element).perform();

3. Double Click

WebElement element = driver.findElement(By.id("doubleClickBtn"));
Actions actions = new Actions(driver);
actions.doubleClick(element).perform();

4. Drag and Drop

WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
Actions actions = new Actions(driver);
actions.dragAndDrop(source, target).perform();

5. Click and Hold / Release

Actions actions = new Actions(driver);
actions.clickAndHold(source).moveToElement(target).release().perform();


6. Keyboard Events Example:

actions.sendKeys(Keys.ENTER).perform();
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();


No comments:

Post a Comment