Working with Action Class in Selenium
The Action Class in Selenium WebDriver is used to handle advanced user interactions such as mouse movements, drag and drop, keyboard events, and more. It allows automation testers to simulate complex actions that can’t be done using standard WebDriver commands like click() or sendKeys().
๐ What is the Action Class?
The Actions class is part of the org.openqa.selenium.interactions package. It provides methods to simulate user interactions like:
- Mouse hover
- Right-click (context click)
- Double-click
- Drag and drop
- Click and hold
- Keyboard events (e.g., shift + click)
๐ ️ Basic Syntax
Actions actions = new Actions(driver);
actions.methodName().build().perform();
build() compiles the sequence of actions.
perform() executes the actions.
✅ Commonly Used Methods in Action Class
Mouse Hover
WebElement element = driver.findElement(By.id("menu"));
Actions actions = new Actions(driver);
actions.moveToElement(element).perform();
Right Click (Context Click)
WebElement element = driver.findElement(By.id("button"));
actions.contextClick(element).perform();
Double Click
WebElement element = driver.findElement(By.id("text"));
actions.doubleClick(element).perform();
Drag and Drop
WebElement source = driver.findElement(By.id("source"));
WebElement target = driver.findElement(By.id("target"));
actions.dragAndDrop(source, target).perform();
Click and Hold
WebElement element = driver.findElement(By.id("box"));
actions.clickAndHold(element).moveByOffset(100, 0).release().perform();
Send Keys with Modifier Keys (e.g., SHIFT)
WebElement input = driver.findElement(By.id("inputBox"));
actions.keyDown(Keys.SHIFT).sendKeys("hello").keyUp(Keys.SHIFT).perform();
⚠️ Best Practices
Always use .perform() to execute actions.
Ensure elements are visible and interactable before performing actions.
Use WebDriverWait for synchronization to avoid flaky tests.
๐งพ Conclusion
The Action Class in Selenium is essential for handling complex interactions during automation testing. Whether it's mouse gestures or keyboard shortcuts, mastering this class enhances your test scripts' flexibility and reliability.
By using the Action Class effectively, testers can simulate real-world user behavior and build more robust Selenium test cases.
Learn Selenium Java Training in Hyderabad
Read More:
Integrating Selenium with Jenkins for CI/CD
Generating Extent Reports in Selenium Java
Debugging Selenium Scripts: Tips and Tools
Handling Dynamic Web Elements in Selenium
Building a Custom Selenium Framework with Java
Visit our IHub Talent Training Institute
Comments
Post a Comment