我必须使用 Selenium 测试 Web 应用程序。 该应用程序具有用于下载文件的链接。 我已经设置了 Firefox 配置文件,以便浏览器在不要求确认的情况下下载文件。我的(简化的)Java 代码如下:
File file = new File("myPath");
driver.findElement(By.id("file-link-download-")).click(); // the download start here
// my test
if(!file.exists()) fail("file does not exist");
我的问题是下载在另一个线程中运行,当执行“我的测试”(如果 file.exists())时,文件尚未下载。我可以将其打包成一种延迟一些的方法,如下所示:
public boolean fileExists(File file) {
try {// Just wait 1000 milliseconds to see if the file exists
Thread.sleep(sleep);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (file.exists()) {
return true;
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
return false;
}
但这并不好,也不够。我认为最好的方法应该是有一个带有超时的单独线程,它会监视文件是否已经下载,然后返回 true 或如果存在超时则返回 false。
处理这个问题的最佳方式(正确方式)是什么?
谢谢!
最佳答案
FluentWait
类专为此类情况而设计。我注意到,您基本上只是在尝试复制本类(class)中已经完成的内容。
下面是它的来源:
它非常通用,因此可以处理各种不同的情况 - 包括您的情况。
您只需检查 apply
方法中的 file.exists()
,如示例文档所示:
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html
关于java - 在java中测试文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19792099/