Run Action Class Selenium Tests on Real Devices

Use Action Class in Selenium to Handle Keyboard & Mouse Events in Selenium. Test on real devices for real-like testing experience

Get Started free
Home Guide How to handle Action class in Selenium

How to handle Action class in Selenium

By Sonal Dwivedi, Community Contributor -

To test an application, one needs to perform a number of user actions on it. To perform any operations on the web application such as double-click, selecting drop-down boxes, etc. the actions class is required. This article discusses how to handle the action class in Selenium.

What is Action Class in Selenium?

Actions class is an ability provided by Selenium for handling keyboard and mouse events. In Selenium WebDriver, handling these events includes operations such as drag and drop in Selenium, clicking on multiple elements with the control key, among others. These operations are performed using the advanced user interactions API. It mainly consists of Actions that are needed while performing these operations.

Action class is defined and invoked using the following syntax:

Actions action = new Actions(driver);

action.moveToElement(element).click().perform();

Methods of Action Class

Action class is useful mainly for mouse and keyboard actions. In order to perform such actions, Selenium provides various methods.

 Mouse Actions in Selenium:

  1. doubleClick(): Performs double click on the element
  2. clickAndHold(): Performs long click on the mouse without releasing it
  3. dragAndDrop(): Drags the element from one point and drops to another
  4. moveToElement(): Shifts the mouse pointer to the center of the element
  5. contextClick(): Performs right-click on the mouse

Keyboard Actions in Selenium:

  1. sendKeys(): Sends a series of keys to the element
  2. keyUp(): Performs key release
  3. keyDown(): Performs keypress without release

Now, let’s understand how to perform various mouse and keyboard actions.

Learn the fundamentals of Selenium coding with the help of Selenium Commands.

BrowserStack Automate Banner 6

Examples of Action Class in Selenium

1. Perform Click Action on the Web Element

Test Scenario: Visit the Browserstack home page and click on the Get Started Free button.

BrowserStack Home Page

Code Snippet:

driver.get("https://www.browserstack.com/");
Actions action = new Actions(driver); 
element = driver.findElement(By.linkText("Get started free"));

action.moveToElement(element).click();

//using click action method

Follow-up Read: Understanding Click Command in Selenium

2. Perform Mouse Hover Action on the Web Element

Test Scenario: Perform Mouse Hover on Live Tab and App Automate Tab on the Browserstack Website.

BrowserStack Products

Code Snippet:

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

public class Mouse {

   public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe");

         WebDriver driver = new ChromeDriver();

       driver.manage().window().maximize();

       driver.get("https://www.browserstack.com/");

       ((JavascriptExecutor) driver).executeScript("scroll(0,300)");

       Actions ac = new Actions(driver);

WebElement live= driver.findElement(By. cssSelector("div.product-cards-wrapper--click a[title='Live']"));     
ac.moveToElement(live).build().perform();

Thread.sleep(3000);

WebElement automate= driver.findElement(By.cssSelector("div.product-cards-wrapper--click a[title='App Automate']"));  automate.click();

Thread.sleep(2000);

//Thread.sleep(4000);

driver.quit();  

   }

}

The code above will perform the mouse hover using Selenium on the Live tab and then move to the App Automate tab and click.

Talk to an Expert

3. Perform Double Click Action on the Web Element

Test Scenario: Perform Double Click Action on Free Trial Button in the Browserstack Home page.

Click on Free Trial - Action Class in Selenium

Code Snippet:

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 Mouse {

public static void main(String[] args) throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

driver.get("https://www.browserstack.com/");

Actions a = new Actions(driver);


//Double click on element

WebElement trialaction = driver.findElement(By.xpath("//a[@id='free-trial-link-anchor']"));

a.doubleClick(trialaction).perform();

   }

}

In the code above, the Action class is created to perform the double click action on the element named Free Trial.

Want to try executing the above code on real browsers and devices on the cloud?

Try Selenium Testing for Free

Learn how to perform various actions on Web Elements using Locators in Selenium.

Note: The Selenium Actions class is useful for performing actions on any element on the screen by specifying x and y coordinates. It is possible to locate more than one web element using the Actions class.

Using Action class in Selenium is of utmost importance in automated testing. This article simplifies the process so that testers know how to simulate common user actions on websites and applications. This lets them monitor software behavior in the real user conditions so that they can verify and optimize user experience for its best possible state. 

How to use Action Class in Selenium on Real Devices using BrowserStack Automate

Below code explains how to click, double click, right click, hover and send keys on web element using Actions class in Selenium on BrowserStack Automate’s Real Device Cloud:

import java.net.MalformedURLException;

import java.net.URL;

import java.util.HashMap;

import org.openqa.selenium.By;

import org.openqa.selenium.MutableCapabilities;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.remote.RemoteWebDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeTest;

import org.testng.annotations.Test;



public class Mouse {



    public static String username = "<username>";

    public static String accesskey = "<access key>";

    public static final String URL = "https://" + username + ":" + accesskey + "@hub-cloud.browserstack.com/wd/hub";

    WebDriver driver;

    String url = "https://www.browserstack.com/";

    Actions act;



    MutableCapabilities capabilities = new MutableCapabilities();

    HashMap<String, Object> bstackOptions = new HashMap<String, Object>();



    @BeforeTest

    public void setUp() throws MalformedURLException {



        capabilities.setCapability("browserName", "Chrome");

        bstackOptions.put("os", "Windows");

        bstackOptions.put("osVersion", "11");

        bstackOptions.put("browserVersion", "latest"); 

        bstackOptions.put("consoleLogs", "info"); 

        bstackOptions.put("seleniumVersion", "3.14.0");

        capabilities.setCapability("bstack:options", bstackOptions);

        driver = new RemoteWebDriver(new URL(URL), capabilities);

        driver.get(url);

        driver.manage().window().maximize();

        act = new Actions(driver);

    }



    @Test

    void doubleClick() {        

        WebElement trialaction = driver.findElement(By.cssSelector("a[title='Free Trial']"));

        //Double click on element

        act.doubleClick(trialaction).perform();

    }



    @Test

    void rightClick() {

        WebElement trialaction = driver.findElement(By.cssSelector("a[title='Free Trial']"));

        //Right click on element

        act.contextClick(trialaction).perform();

    }



    @Test

    void hover() {

        WebElement products = driver.findElement(By.cssSelector("button#products-dd-toggle"));

        //Mouse hover on element

        act.moveToElement(products).perform();

    }



    @Test

    void clickAndsendKeys() {

        WebElement search = driver.findElement(By.xpath(

                "//button[@class='bstack-mm-search-menu doc-search-menu dropdown-toggle doc-search-cta doc-search-menu-icon doc-menu-toggle hide-sm hide-xs']"));

        //Click on element

        act.click(search).perform();

        WebElement searchBox = driver.findElement(By.cssSelector("input#doc-search-box-input"));

        //Send keys on element

        act.sendKeys(searchBox, "Selenium").perform();

    }



    @AfterMethod

    void tearDown() {

        driver.get(url);

    } 

}

Why use BrowserStack Automate for Selenium Tests?

Here’s why you should use BrowserStack Automate to run your Selenium Tests:

  • Parallel Testing: BrowsersStack’s Automate product supports parallel testing by which one can easily test their app on a pool of combinations of device and browser types.
  • Real Devices and Browsers: With Automate one can test on any latest mobile device or web browser without the overhead of purchasing a physical device as tetsing on real devices and browsers gives the actual confidence about the applications’ functionality and performance.
  • Dedicated Dashboard: Running Selenium test cases on Automate product, creates a report in a dashboard which can be referred to manage and monitor the automation testing activities. Report contains details such as Pass/Fail/Pending status, environment details (device name, OS version, Platform, browser name, browser version), test execution time and duration, screenshots, etc.
  • Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for the automated test execution. With this feature it allows to customize the structure and content of the report as per user’s need. 
  • Easy Integration with CI/CD Pipeline: BrowserStack’s Automate product can be seamlessly integrated with popular CI/CD tools such as Jenkins, TeamCity, TravisCI. 

Conclusion

The Actions class in Selenium plays a vital role in automating mouse and keyboard events in web applications. It provides various methods such as click, mouse hover, double click, content click, drag and drop to simulate actions on web elements. 

With Actions class one can interact with the website in the same way as a real time user would allowing them to test and verify complex interactions. This lets them monitor software behavior in the real user conditions so that they can verify and optimize user experience for its best possible state. 

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

How to handle multiple windows in Selenium?

How to Drag and Drop in Selenium?

Test Action Class in Selenium on Real Devices

Run Action Class in Selenium Tests on Real Devices Cloud for accurate results