0

我正在使用下面的代码在我的应用程序中选择和导入一个 csv 文件。文件路径被粘贴,我还可以看到数据被导入,但我的测试用例仍然失败,我无法弄清楚原因。

public static void uploadFileFromFolder(String objectType, String objectName, String data) {
        // creating instance of Robot class
        try {
            StringSelection ss = new StringSelection(data);
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
            // paste file path in windows pop-up
            Robot robot = new Robot();
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
        } catch (AWTException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
4

1 回答 1

-1

如果坚持使用机器人方法并不重要,我建议您以这种方式处理文件上传:

// Find file input element
WebElement input = driver.findElement(By.cssSelector("input[type='file']"));

// Make sure element is visible
((JavascriptExecutor) driver).executeScript("arguments[0].style.display = 'block';", input);

// Specify you local file path here
input.sendKeys("/path/to/file/on/machine/which/runs/tests");

如果是 RemoteDriver,请不要忘记添加:

// Configure your client to upload local files to remote Selenium instance
    driver.setFileDetector(new LocalFileDetector());

注意:文件路径应该是绝对的。你可以这样做:

String getFilePath(String filePath) {
    new File(filePath).absolutePath
}
于 2019-02-12T14:21:30.270 回答