What is Action Class
Ducat India
India’s Most Trusted IT Training School, 100% placement for all courses. Apply Today or follow our page updates.
What is Action Class
The Action class is user-facing API for emulating complex user action events. The Webdriver use the Action Class to perform keyboard events and mouse events such as drag and drop or clicking multiple elements while holding down the Control key. The Action class Implements builder pattern, in which a complex object is constructed that can be further used to create different representation of same object. The action events are found in org.openqa.selenium.interactions.Actions class.
Here is the code snippet for using actions:
Perform method is used here to execute the action. The sequence of actions should be minimal.
Example:
package automationFramework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
public class mouseHover{
public static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.onlinestore.toolsqa.wpengine.com");
WebElement element = driver.findElement(By.linkText("Product Category"));
Actions action = new Actions(driver);
action.moveToElement(element).build().perform();
driver.findElement(By.linkText("iPads")).click();
}
}
What Can We Do With Action Class
Selenium action classes enable to perform advanced activities such as Right-click, Mouse Hover, Pressing any keys on the keyboard, Double click, Click and Hold, Releasing the pressed keys on the keyboard, Scrolling, Drag and Drop. These advanced activities lower the burden of complex codes of the programming languages and allow to just call the methods for the respective activities. To use Actions class, we just need to import the
org.openqa.selenium.interactions.Actions class
Keyboard Interactions using Actions API
In keyboard interaction, normally we consider events such as scrolling the element and focusing on it. With the help of Action API, keyboard interactions are easier now. In Advanced User Interactions API, absolute interaction with element is possible either by clicking on element or sending a Keys.TAB before sending text.
Actions Class Method for Keyboard Interaction
Code snippet for Keyboard Actions
WebElement textBoxElement = driver.findElement(By Locator of textBoxElement);
Actions builder = new Actions(driver);
Action typeInCAPS = builder.keyDown(textBoxElement, Keys.SHIFT)
.sendKeys(textBoxElement, "artOfTesting")
.keyUp(textBoxElement, Keys.SHIFT)
.build();
typeInCAPS.perform();
Mouse Interactions using Actions API
In mouse actions we use current location of the element as a standard. First action will be relative to
the location of the standard element, the next action will be relative to the location of the mouse at the end of the last action, etc.
Actions Class Method for Mouse Interactions
Code snippet for a Mouse Action
WebElement rtClickElement = driver.findElement(By Locator of rtClickElement);
Actions rightClickAction = new Actions(driver).contextClick(rtClickElement);
rightClickAction.build().perform();
Actions builder = new Actions(driver);
WebElement dragElement=driver.findElement(By.id(“draggable”));
WebElement dropElement=driver.findElement(By.id(“droppable”));
To hold the drag element and then move it to drop element location
Action dragDrop = builder.clickAndHold(dragElement).moveToElement(dropElement).b uild();
To Execute the drag and drop Action
dragDrop.perform();
If you want to click on menu option in mouse hover menu, then follow this code:
Actions builder = new Actions(driver);
WebElement menu = driver.findElement(By.id(“menu”));
WebElement menuoption =
driver.findElement(By.id(“menuoption”));
Move to the main menu option and then sub-option
Action element= builder.moveToElement(menu).moveToElement(menuoption).build();
To Execute the Action
element.perform();
It’s evident from the above examples that using “Actions API” in Webdriver simplifies input interactions. In fact some events can be only handled by Action API e.g. Drag and drop.
Code snippet to right click an element
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId")); action.contextClick(element).perform();
Here, it is instantiating an object of Actions class. After that, it pass the WebElement to be right clicked as parameter to the contestClick() method present in the Actions class. Then, it call the perform() method to perform the generated action.
Sample code to right click an element
For the demonstration of the right click action, it will be launching Sample Site for Selenium Learning. Then on right-click a textbox, its context menu will get displayed, asserting that right click action is successfully performed.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class RightClick {
public static void main(String[] args) throws InterruptedException{
WebDriver driver = new FirefoxDriver();
//Launching Sample site
driver.get("https://artoftesting.com/sampleSiteForSelenium.html
");
//Right click in the TextBox
Actions action = new Actions(driver);
WebElement searchBox = driver.findElement(By.id("fname"));
action.contextClick(searchBox).perform();
//Thread.sleep just for user to notice the event Thread.sleep(3000);
//Closing the driver instance
driver.quit();
}
}
Code snippet to double click an element
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId")); action.doubleClick(element).perform();
Here, it is instantiating an object of Actions class. After that, it pass the WebElement to be double clicked as parameter to the doubleClick() method present in the Actions class. Then, call the perform() method to perform the generated action.
Sample code to double click an element
For the demonstration of the double click action, it will be launching Sample Site for Selenium Learning. Then it will double click the button on which the text “Double-click to generate alert box” is written. After that an alet box will appear, asserting that double-click action is successfully performed.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class DoubleClick {
public static void main(String[] args) throws InterruptedException{
WebDriver driver = new FirefoxDriver();
//Launching sample website
driver.get(https://artoftesting.com/sampleSiteForSelenium.
html);
driver.manage().window().maximize();
//Double click the button to launch an alertbox
Actions action = new Actions(driver);
WebElement btn = driver.findElement(By.id("dblClkBtn"));
action.doubleClick(btn).perform();
//Thread.sleep just for user to notice the event Thread.sleep(3000);
//Closing the driver instance
driver.quit();
}
}
领英推荐
Example to show how to use Actions class with doubleClick() and perform() methods to double click on element.
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class DoubleClick {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://only-testing-blog.blogspot.in/2014/09/selectable.html");
}
@Test
public void doubleClick_Button() throws IOException,
InterruptedException {
WebElement ele =
driver.findElement(By.xpath("https://button[contains(.,'Double-Click Me To See Alert')]"));
//To generate double click action on "Double-Click Me To See Alert" button.
Actions action = new Actions(driver);
action.doubleClick(ele); action.perform();
Thread.sleep(3000);
String alert_message = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
System.out.println(alert_message);
}
}
On run this code, It will double click on “Double-Click Me To See Alert”. Rest of code Is to handle alert generated by button double click. So this Is the way to double click on any element In selenium webdriver test.
Mouse Hover and Mouse Movement with Action
In order to perform mouse hover actions, all of the actions need to be chain which to achieve in one go. The WebDriver need to be move to the parent element that has child elements and click on the child element. With the object of the Actions class, Webdriver moves to the main menu and then to the sub menu and click on it.
Few of the scenarios are:
WebElementele = driver.findElement(By.xpath("xpath"));
//Create object 'action' of an Actions class Actions action = new Actions(driver);
//Mouseover on an element action.moveToElement(ele).perform();
//Main Menu
WebElementmainMenu =
driver.findElement(By.linkText("main_menu_link"));
//Create object 'action' of an Actions class
Actions actions = new Actions(driver);
//To mouseover on main menu
actions.moveToElement(mainMenu);
//Sub Menu
WebElementsubMenu =
driver.findElement(By.linkText("sub_menu_link"));
//To mouseover on sub menu actions.moveToElement(subMenu);
//build() method is used to compile all the actions into a single step
actions.click().build().perform();
Example to Handle Mouseover Action Using Selenium Actions Class:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class MouseHoverExample {
public static void main(String[] args) throws Exception {
// Initialize WebDriver
WebDriver driver = new FirefoxDriver();
// Wait For Page To Load driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
// Go to URL
driver.get("https://www.myntra.com/");
// Maximize Window
driver.manage().window().maximize();
// Mouse Over On " Men link "
Actions act = new
Actions(driver); By testlink =
By.linkText("Men");
WebElement test = driver.findElement(testlink);
act.moveToElement(test).build().perform();
// Click on " bags & backpacks " link driver.findElement(By.linkText("Bags & Backpacks")).click();
// Click on the categories - Bag-packs
driver.findElement(By.xpath("https://*[text()='Categories']//following::l i[1]/label")).click();
// Mouse Hover on the 1st bag
Actions sel = new Actions(driver);
sel.moveToElement(driver.findElement(By.xpath("https://ul[@class='results small']/li[1]"))).build().perform();
// Click on the "Add to Bag" icon of the 1st
bag
driver.findElement(By.xpath("https://ul[@class='results
small']/li[1]/div[1]//div")).click();
// Hover over the shopping bag icon present on the
top navigation bar
Actions mov = new Actions(driver);
mov.moveToElement(driver.findElement(By.xpath("https://a[contains(@class, 'cart')]//div"))).click().build().perform();
// Click on the remove icon driver.findElement(By.xpath("(//span[@data-hint='REMOVE FROM
BAG'])[1]")).click();
// Closing current driver
window driver.close();
}
}
Finding Coordinates of a Web Object
Any software web element has its own position on page and generally it is measured in x and y pixels and known as x y coordinates of element. x pixels means horizontal position on page from left side and y pixels means vertical position on software web page from top side. In selenium WebDriver software testing tool, x y coordinates of element can be get by using Point class.
Example:
importjava.util.concurrent.TimeUnit;
importorg.openqa.selenium.By;
importorg.openqa.selenium.Point;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.firefox.FirefoxDriver;
importorg.testng.annotations.BeforeTest;
importorg.testng.annotations.Test;
public class xyCoordinates {
WebDriver driver;
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://only-testing-
blog.blogspot.in/2014/09/selectable.html");
}
public void getCoordinates() throws Exception {
//Locate element for which you wants to retrieve x y coordinates.
WebElement Image =
driver.findElement(By.xpath("https://img[@border='0']"));
//Used points class to get x and y coordinates of element.
Point point = Image.getLocation();
intxcord = point.getX();
System.out.println("Element's Position from left side Is "+xcord +" pixels.");
intycord = point.getY();
System.out.println("Element's Position from top side Is "+ycord +" pixels.");
}
}
Output:
Element's Position from left side Is 76 pixels. Element's Position from top side Is 740 pixels.
Drag and Drop Action
In some applications, a situation may be face to automate drag and drop an item from one location to another location. These could not be achieve by using basic elements. The Actions class has two methods that support Drag and Drop.
Actions.dragAndDrop(Sourcelocator, Destinationlocator)
Example:
importorg.openqa.selenium.By; importorg.openqa.selenium.WebDriver; importorg.openqa.selenium.WebElement; importorg.openqa.selenium.chrome.ChromeDriver; importorg.openqa.selenium.interactions.Actions; importorg.testng.annotations.Test;
public class DragAndDrop { WebDriver driver;
@Test
public void DragnDrop()
{
System.setProperty("webdriver.chrome.driver"," E://Selenium//Selenium_Jars//chromedriver.exe ");
driver= new ChromeDriver();
driver.get("https://www.ducatindia.com/test/drag_drop.html");
//Element which needs to drag.
WebElement
From=driver.findElement(By.xpath("https://*[@id='credit2']/a"));
//Element on which need to drop.
WebElement To=driver.findElement(By.xpath("https://*[@id='bank']/li"));
//Using Action class for drag and drop.
Actions act=new Actions(driver);
//Dragged and dropped.
act.dragAndDrop(From, To).build().perform();
}
}
In the above code we launch the given URL in Firefox browser and then drag the BANK element and drop on the DEBIT SIDE block through dragAndDropmethod as explained below
WebElement From=driver.findElement(By.xpath("https://*[@id='credit2']/a"));
WebElement To=driver.findElement(By.xpath("https://*[@id='bank']/li"));
Actions act=new Actions(driver);
act.dragAndDrop(From, To).build().perform();
Example: There is a Checklist on the left side and there are four sub menus with the name of DragAndDrop-[1-3]. We will login to this website and then drag DragAndDrop-1 to DragAndDrop-4 of the left side sub menu.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class DragAndDrop {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
String URL = "https://sandbox.checklist.com/account/";
driver.get(URL);
driver.findElement(By.name("j_username")).sendKeys("Username");
driver.findElement(By.name("j_password")).sendKeys("Password);
driver.findElement(By.name("login")).click();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
WebElement From = driver.findElement(By.xpath(".//*[@id='userChecklists']
/li[1]/a/span"));
WebElement To = driver.findElement(By.xpath(".//*[@id='userChecklists']/l i[4]/a/span"));
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(From)
.moveToElement(To)
.release(To)
.build();
dragAndDrop.perform();
}
}
Robot Class
Sometime in testing process it is required to control mouse and keyboard to connect with windows. For example to handle pop-ups, file upload and download. These windows applications are not handled by Selenium Webdriver.
To handle these pop-ups there is a Robot Class which interacts with OS pop/ups.
Role of Robot Class
Initialization in scripts
Robot Class is part of java.awt.package.
There are two packages required to import for Robot Class.
import java.awt.AWTException;
import java.awt.Robot;
Create object of Robot Class
Robot robot= new Robot();
Popular methods used in Robot class are
robot.mouseMove(coordinates.getX(), coordinates.getY());
For example, if the task is to type ‘A’ (caps+a) using keyboard event. The code will be like
Robot robot= new Robot();
//press CTRL+a
robot.keyPress(KeyEvent.VK_CONTROL);
Robot.keyPress(KeyEvent.VK_a);
//release CTRL+a
robot.keyPress(KeyEvent.VK_CONTROL);
Robot.keyPress(keyEvent.VK_a);
File upload using Robot Class
Common steps to upload the file using Robot class are
Disadvantages of Robot Class
There are few disadvantages of Robot framework
Summary