Perform drag and drop operation

While performing test automation some actions can not be performed directly in webdriver, in such a case we need to use some tricky ways. Some of such scenarios are sending keyboard inputs to your test or mouse operations on web-elements, etc.

keyboard and mouse events in selenium webdriver

Special keyboard and mouse events are performed using the Advanced User Interactions API. It contains the Actions and the Action classes that are needed when executing these events. 

We need to create new action builder instance by passing the webdriver instance. The following are the most commonly used keyboard and mouse events provided by the Actions class. 

Following are some example selenium methods of action class to handle such scenarios.

keyboard and mouse events in selenium webdriver

Example code:
Example 1: To perform Mouse hover action.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Actions actions = new Actions(driver);

WebElement mainMenu = driver.findElement(By.linkText("menulink"));

actions.moveToElement(mainMenu);

WebElement subMenu = driver.findElement(By.cssSelector("subLinklocator"));

actions.moveToElement(subMenu);
actions.click().build().perform();


Example 2: 'build()' method is used to compile all the list of actions into a single step and ready to be performed.
1
2
3
4
5
Actions action = new Actions(driver);

WebElement mainMenu = driver.findElement(By.linkText("MainMenu"));

action.moveToElement(mainMenu).moveToElement(driver.findElement(By.xpath("submenuxpath"))).click().build().perform();

Example 3: To perform drag and drop.

1
2
Actions action = new Actions(driver);
action.dragAndDrop(Sourcelocator, Destinationlocator).build().perform();


Example 4: To perform right click.
1
2
Actions action= new Actions(driver);
action.contextClick(MyLink).build().perform();

Example 5: To perform double click.
1
2
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.id("Name"))).doubleClick().build().perform();


<-- Previous || Next -->

1 comment: