项目中,存在点击后下载的业务流程,而selenium本身没有很好的方法去断言文件是否下载成功。此时我们可以通过WatchService去监听目录文件,来确定文件是否下载成功。
//监听所下载的文件名
public static String getDownloadedDocumentName(String filepath, String filename)
{
String downloadedFileName = null;
boolean valid = true;
boolean found = false;
//default timeout in seconds
long timeOut = 30;
try
{
Path downloadFolderPath = Paths.get(filepath);
WatchService watchService = FileSystems.getDefault().newWatchService();
downloadFolderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
long startTime = System.currentTimeMillis();
do
{
WatchKey watchKey;
watchKey = watchService.poll(timeOut,TimeUnit.SECONDS);
long currentTime = (System.currentTimeMillis()-startTime)/1000;
if(currentTime>timeOut)
<