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 java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
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="https://file-examples.com/index.php/sample-documents-download/sample-doc-download/";
//Open Browser
@BeforeTest
public void browser(){
System.setProperty("webdriver.chrome.driver","C:/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}
// Download the file and Validate file with Name
@Test
public void verifywithName(){
driver.get(URL);
driver.findElement(By.xpath("//*[@id='table-files']/tbody/tr[1]/td[3]/a")).click();
Assert.assertTrue(isFileDownloaded(fileDownloadpath, "file-sample_100kB.doc"), "Failed to download Expected document");
}
// Check the downloaded file in the download folder
@Test
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();
}
}
Result:
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"),