简体   繁体   中英

Can't get Selenium drag and drop test to work (Java)

I'm trying to perform Selenium's dragAndDrop function in Java. Right now, i'm testing with this page. It contains an image and two divs:

在此处输入图片说明

I'm trying to test dragging the image to just the green div for now. I was able to come up with this Java code:

public static void main(String args[]) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://localhost:8012/dragTest/dragAndDropTest.html");

    Thread.sleep(1000);
    driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);

    //Element to be dragged
    driver.findElement(By.xpath("//*[@id=\"drag1\"]")).click();
    WebElement from = driver.findElement(By.xpath("//*[@id=\"drag1\"]"));

    //Element to drag to
    WebElement to = driver.findElement(By.xpath("//*[@id=\"div1\"]"));

    //Use Action class for drag and drop
    Actions builder = new Actions(driver);

    //Drag and drop drag1 to div1
    builder.dragAndDrop(from, to).perform();
    builder.build();
}

I'm able to run the test, but nothing happens. I added console logs to test if the code even clicks on the image prior to dragging, and that works (the clicking works), it's just the image doesn't get dragged.

I've looked around for help and noticed that a lot of drag and drop Selenium code look like this. So I'm not sure where I'm going wrong.

Instead of :

builder.dragAndDrop(from, to).perform();
builder.build();

Try:

builder.dragAndDrop(from, to).build().perform();

I think this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM