How to drag and drop using selenium

As software testers, we often need to verify application features that involve drag and drop functionality. Selenium provides the Actions class (or Action interface) to handle advanced user interactions such as drag and drop. By specifying the source element (to drag) and the target element (to drop), we can easily automate this action using Selenium.

Below is an example Selenium with java script that demonstrates drag and drop using Actions:

✅Example Script:

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.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class DragAndDropTest {
WebDriver driver;

@BeforeClass
public void setUp() {
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://jqueryui.com/droppable/"); // Example drag-drop site
    driver.switchTo().frame(0); // Switch to iframe where draggable/droppable exists
}

@Test
public void testDragAndDrop() {
    WebElement source = driver.findElement(By.id("draggable"));
    WebElement target = driver.findElement(By.id("droppable"));

    Actions actions = new Actions(driver);
    actions.dragAndDrop(source, target).perform();

    // Assertion to verify drop success
    String droppedText = target.getText();
    Assert.assertEquals(droppedText, "Dropped!", "Drag and Drop failed!");
}

@AfterClass
public void tearDown() {
    if (driver != null) {
        driver.quit();
    }
}

}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , CodesToolbox
Scroll to Top
0
Would love your thoughts, please comment.x
()
x