Drag and drop lets you test if you can move items on a webpage by clicking and dragging them. It checks if the page reacts correctly when you move things around.
0
0
Drag and drop in Selenium Java
Introduction
Testing a shopping cart where you drag products to add them.
Rearranging items in a list by dragging them up or down.
Moving files or icons on a web desktop interface.
Testing games or apps that require dragging objects.
Checking if drag and drop upload areas accept files.
Syntax
Selenium Java
Actions actions = new Actions(driver); actions.dragAndDrop(sourceElement, targetElement).perform();
Actions is a Selenium class to handle complex mouse and keyboard actions.
dragAndDrop takes two elements: the one to drag and where to drop it.
Examples
Drag element with id 'drag1' and drop it on element with id 'drop1'.
Selenium Java
WebElement source = driver.findElement(By.id("drag1")); WebElement target = driver.findElement(By.id("drop1")); Actions actions = new Actions(driver); actions.dragAndDrop(source, target).perform();
Alternative way: click and hold source, move to target, then release.
Selenium Java
WebElement source = driver.findElement(By.cssSelector(".item")); WebElement target = driver.findElement(By.cssSelector(".container")); Actions actions = new Actions(driver); actions.clickAndHold(source).moveToElement(target).release().perform();
Sample Program
This test opens a page with a drag and drop demo, drags the box, and checks if the drop was successful by reading the text.
Selenium Java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class DragAndDropTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://jqueryui.com/droppable/"); driver.switchTo().frame(0); // Switch to demo frame WebElement source = driver.findElement(By.id("draggable")); WebElement target = driver.findElement(By.id("droppable")); Actions actions = new Actions(driver); actions.dragAndDrop(source, target).perform(); String textAfterDrop = target.getText(); if ("Dropped!".equals(textAfterDrop)) { System.out.println("Test Passed: Drag and drop worked."); } else { System.out.println("Test Failed: Drag and drop did not work."); } } finally { driver.quit(); } } }
OutputSuccess
Important Notes
Make sure the elements are visible and interactable before dragging.
Switch to the correct frame if the drag and drop elements are inside an iframe.
Use explicit waits if needed to wait for elements to load.
Summary
Drag and drop tests moving elements by mouse actions.
Use Selenium's Actions class with dragAndDrop or clickAndHold/moveToElement/release.
Check the result by verifying changes on the page after dropping.