转自: http://www.seleniumeasy.com/selenium-tutorials/verify-file-after-downloading-using-webdriver-java
It is very important to verify if the file is downloaded successful or not. Most of the cases we just concentrate on clicking the downloaded button. But at the same time it is also very important to confirm that file is downloaded successfully without any errors or if some other file is getting downloaded.
In most of the cases we know which file is getting downloaded after clicking on download button / link. Now when we know the file name, we can verify using java for the 'File Exists' in a downloaded folder location which we specify.
Even there are cases where file name is not unique. File name may be generated dynamically. In such cases we can also check for the file exists with the file extension.
We will see all the above cases and verify for the file which is being downloaded. We will see examples using Java File IO and WatchService API
package com.pack; import java.io.File; import java.io.FileFilter; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.apache.commons.io.comparator.LastModifiedFileComparator; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class FileDownloadVerify { private WebDriver driver; private static String downloadPath = "D:\\seleniumdownloads"; private String URL="http://spreadsheetpage.com/index.php/file/C35/P10/"; @BeforeClass public void testSetup() throws Exception{ driver = new FirefoxDriver(firefoxProfile()); driver.manage().window().maximize(); } @Test public void example_VerifyDownloadWithFileName() { driver.get(URL); driver.findElement(By.linkText("mailmerge.xls")).click(); Assert.assertTrue(isFileDownloaded(downloadPath, "mailmerge.xls"), "Failed to download Expected document"); } @Test public void example_VerifyDownloadWithFileExtension() { driver.get(URL); driver.findElement(By.linkText("mailmerge.xls")).click(); Assert.assertTrue(isFileDownloaded_Ext(downloadPath, ".xls"), "Failed to download document which has extension .xls"); } @Test public void example_VerifyExpectedFileName() { driver.get(URL); driver.findElement(By.linkText("mailmerge.xls")).click(); File getLatestFile = getLatestFilefromDir(downloadPath); String fileName = getLatestFile.getName(); Assert.assertTrue(fileName.equals("mailmerge.xls"), "Downloaded file name is not matching with expected file name"); } @AfterClass public void tearDown() { driver.quit(); }