为了实现对Selenium测试的拖放,我提到http://elementalselenium.com/tips/39-drag-and-drop在那里提到了使用javascript(从https://gist.github.com/rcorreia/2362544)来处理拖放操作。无法执行使用JavaScript进行HTML5拖放Selenium WebDriver测试
我实现它,因为它是它的工作。但在我的情况下,我有源和目标元素的动态xpaths。为了实现这一目标,我试着用下面的代码:
package org.test.selenium;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class HTML5DragAndDrop {
WebDriver driver = null;
@BeforeClass
public void setUp(){
System.out.println(System.getProperty("user.dir"));
String chromeDriver = System.getProperty("user.dir")+ File.separator + "drivers" + File.separator + "chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chromeDriver);
driver = new ChromeDriver();
driver.get("http://the-internet.herokuapp.com/drag_and_drop");
}
@AfterClass
public void tearDown(){
driver.quit();
}
@Test
public void testDragAndDrop() throws IOException, InterruptedException {
String filePath = "C://dnd.js";
String source = "//div[@id='column-a']";
String target = "//div[@id='column-b']";
StringBuffer buffer = new StringBuffer();
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while((line = br.readLine())!=null)
buffer.append(line);
String javaScript = buffer.toString();
javaScript = javaScript + "$('" + source + "').simulateDragDrop({ dropTarget: '" + target + "'});";
((JavascriptExecutor)driver).executeScript(javaScript);
}
}
,但它给错误:
org.openqa.selenium.WebDriverException: unknown error: Runtime.evaluate threw exception: SyntaxError: Unexpected identifier
(会话信息:铬= 35.0.1916.153)
然而,如果用源和目标为像以下css,它工作得很好:
String source = "#column-a";
String target = "#column-b";
有人可以请建议我改变需要这样做才能使上面的代码和xpaths一起使用源和目标元素?在我的情况下,我受限于使用xpath,我只能用xpath来完成此操作。