Why complex gestures need Actions API in Selenium Java - Automation Benefits in Action
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; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals; public class DragAndDropTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("https://jqueryui.com/droppable/"); // Switch to frame containing draggable and droppable elements wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe.demo-frame"))); WebElement draggable = wait.until(ExpectedConditions.elementToBeClickable(By.id("draggable"))); WebElement droppable = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("droppable"))); Actions actions = new Actions(driver); actions.clickAndHold(draggable) .moveToElement(droppable) .release() .perform(); String dropText = droppable.getText(); assertEquals("Dropped!", dropText, "Droppable text should be 'Dropped!' after drop"); } finally { driver.quit(); } } }
This test automates a drag and drop gesture using Selenium WebDriver with Java.
First, it opens the web page with draggable and droppable elements inside an iframe, so it switches to that iframe.
It waits explicitly for the draggable and droppable elements to be ready to interact.
Then it uses the Actions class to perform the complex gesture: click and hold the draggable element, move it over the droppable element, and release the mouse button.
Finally, it asserts that the droppable element's text changed to 'Dropped!' to confirm the action succeeded.
This approach is necessary because simple click commands cannot simulate drag and drop gestures, which require a sequence of mouse actions.
Now add data-driven testing with 3 different draggable and droppable element pairs on the page