Validating Downloaded File Using Selenium

| By Webner

Validating downloaded files in automation testing

In the manual testing process, it is easy validating that the file is downloaded or not because the human mind is fully involved in the testing process. But in the case of automation testing, it is important to verify that the file is downloaded without any error and the downloaded file after clicking on the download button/links is correct because this process is achieved by code. We can verify the file using the Java code from the downloaded location if we know the name and extension of the file.

Here is an example of code to verify the downloaded file with name:

Package File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Validatefile {
private static WebDriver driver;
private static String fileDownloadpath = "C:\\Users\\Downloads";
private String URL="";
//Open Browser
public void browser(){
driver = new ChromeDriver();
// Download the file and Validate file with Name
public void verifywithName(){
Assert.assertTrue(isFileDownloaded(fileDownloadpath, "file-sample_100kB.doc"), "Failed to download Expected document");
// Check the downloaded file in the download folder
public boolean isFileDownloaded(String fileDownloadpath, String fileName) {
boolean flag = false;
File directory = new File(fileDownloadpath);
File[] content = directory.listFiles();
for (int i = 0; i < content.length; i++) { if (content[i].getName().equals(fileName)) return flag=true; } return flag; } //Quit from browser @AfterClass public void closebrowser(){ driver.quit(); } }


We can also verify the downloaded file with the file extension. For that, we need to pass the extension of a file instead of the name. Such as given in below code:
Assert.assertTrue(isFileDownloaded(fileDownloadpath, "doc"),

Leave a Reply

Your email address will not be published. Required fields are marked *