My Thoughts: Handling "drag and drop" actions using WebDriver(Selenium 2)

Tuesday, June 19

Handling "drag and drop" actions using WebDriver(Selenium 2)


Automating rich web application is even more interesting since it involves advanced user interactions.

Say we have a web application which drag an item from one location and then drop it at another location.These kind of drag and drops are cant be automated with one single statement .In WebDriver we have a separatae "Actions" class to handle advanced user interactions(say drag and drop) on web page.

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

Here is the sample code using TestNG framework
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
 }
}