项目中,存在点击后下载的业务流程,而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)
{
System.out.println("Download operation timed out.. Expected file was not downloaded");
return downloadedFileName;
}
for (WatchEvent<?> event: watchKey.pollEvents())
{
WatchEvent.Kind<?> kind = event.kind();
if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE))
{
String fileName = event.context().toString();
System.out.println("New File Created:" + fileName);
if(fileName.endsWith(filename))
{
downloadedFileName = fileName;
System.out.println("Downloaded file found with extension " + filename + ". File name is " + fileName);
Thread.sleep(500);
found = true;
break;
}
}
}
if(found)
{
return downloadedFileName;
}
else
{
currentTime = (System.currentTimeMillis()-startTime)/1000;
if(currentTime>timeOut)
{
System.out.println("Failed to download expected file");
return downloadedFileName;
}
valid = watchKey.reset();
}
} while (valid);
}
catch (InterruptedException e)
{
System.out.println("Interrupted error - " + e.getMessage());
e.printStackTrace();
}
catch (NullPointerException e)
{
System.out.println("Download operation timed out.. Expected file was not downloaded");
}
catch (Exception e)
{
System.out.println("Error occured - " + e.getMessage());
e.printStackTrace();
}
return downloadedFileName;
}
//确认文件下载是否完成
public static Boolean isFileDownloaded_Ext(String filepath, String filename) {
boolean flag=false;
File dir = new File(filepath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
flag = false;
}
for (int i = 0; i <files.length; i++) {
if(files[i].getName().contains(filename)) {
flag=true;
}
}
return flag;
}
通过上面的方法即可得到下载后的文件名,然后通过下载的文件和用例中的预期做断言即可
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。