DragAndDrop divs are in a Frame, First we need to switch to the frame before performing drag and drop. And then we also need to check for the availability of SourceElement and DestinationElements.
Syntax for drag and drop
Actions action = new Actions(driver);
action.dragAndDrop(Sourcelocator, Destinationlocator).build().perform();
We can also make it as below:
(new Actions(driver)).dragAndDrop(element, target).perform();
We have also used Webdriver Wait Expected conditions to wait for a frame to be available and then switch to the frame.
package dayOne;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DragAndDrop {
WebDriver driver;
@Test
public void testDragAndDropExample() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("http://jqueryui.com/droppable/");
//Wait for the frame to be available and switch to it
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector(".demo-frame")));
WebElement Sourcelocator = driver.findElement(By.cssSelector(".ui-draggable"));
WebElement Destinationlocator = driver.findElement(By.cssSelector(".ui-droppable"));
dragAndDrop(Sourcelocator,Destinationlocator);
String actualText=driver.findElement(By.cssSelector("#droppable>p")).getText();
Assert.assertEquals(actualText, "Dropped!");
}
}
simple method to perform drag and drop. But before performing we also need to check if both the elements SourceElement and DestinationElements are available
public void dragAndDrop(WebElement sourceElement, WebElement destinationElement)
{
(new Actions(driver)).dragAndDrop(sourceElement, destinationElement).perform();
}
}