Monday, 26 May 2014

Working Example Of DragAndDrop Using WebDriver

WebDriver uses Actions class to drag and drop.
Actions class is found in package org.openqa.selenium.interactions

There are 2 methods related to drag and drop:
1. dragAndDropBy(WebElement elment,int x, int y)
//This will drag WebElement element to location is defined by x and y coordinate.
2. dragAndDrop(WebElement a, WebElement b)
//This will drag WebElement a and drop to WebElement b


Working Example:

// Initializing FirefoxDriver
 WebDriver driver = new FirefoxDriver();
 /* Loading the site on which we need to perform the
  drag and drop action.*/
 driver.get("http://jqueryui.com/droppable/");
 driver.manage().window().maximize();
 // Waiting for element to load
 Thread.sleep(5000);
 /* Drag and drop features are usually part of the iframes.
 So we first need to switch to the iframe so that selenium
 can locate the web element.*/
 List<WebElement> frames=driver.findElements(By.tagName("iframe"));

 driver.switchTo().frame(frames.get(0));
 //WebElement box = driver.findElement(By.xpath("html/body/div[1]"));
 WebElement box = driver.findElement(By.id("draggable"));

 /* Creating the object of Actions class and passing the
  driver to it. It should be noted that Actions(WebDriver driver)
  is an argument constructor which take driver as argument.*/
 Actions act = new Actions(driver);
 act.dragAndDrop(box, driver.findElement(By.id("droppable"))).build().perform();
 driver.switchTo().defaultContent();
 driver.close();

No comments:

Post a Comment