Handling "drag and drop" actions using Selenium WebDriver

11 January, 2014
Automating rich web application is very interesting as it involves advanced user interactions.

Say we have a web application which drags an item from one location and then drops it at another location. This kind of drag and drops cannot be automated with single statement. We need to use "Actions" class in WebDriver to handle advanced user interactions on web page.

More documentation on how to automate advanced user interactions:
http://code.google.com/p/selenium/wiki/AdvancedUserInteractions

Below is the sample code using TestNG framework:

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.firefox.FirefoxProfile;  
import org.openqa.selenium.interactions.Action;  
import org.openqa.selenium.interactions.Actions;  
import org.testng.annotations.BeforeTest;  
import org.testng.annotations.Test;  
  
public class DragAndDrop {  
   
 WebDriver driver;  
   
 @BeforeTest  
 public void start(){  
  FirefoxProfile profile = new FirefoxProfile();  
  profile.setEnableNativeEvents(true);  
  driver = new FirefoxDriver(profile);  
 }  
  
 @Test  
 public void start1(){  
  driver.get("http://jqueryui.com/droppable/");  
  driver.switchTo().frame(0);    
  driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);  
  WebElement dragElement=driver.findElement(By.id("draggable"));  
  WebElement dropElement=driver.findElement(By.id("droppable"));  
      
  Actions builder = new Actions(driver);  // Configure the Action  
  Action dragAndDrop = builder.clickAndHold(dragElement)  
    .moveToElement(dropElement)  
    .release(dropElement)  
    .build();  // Get the action  
    dragAndDrop.perform(); // Execute the Action  
 }  
}

No comments:

Post a Comment