Most of
the selenium user is facing problem while handling file download scenario.
In file downloading
we have to deal with windows pop-up also we need to verify whether file is
downloaded or not.
To deal
with this scenario with have to work with firefox profile.
Below you
can check the code, here you can verify file by its name or if name is randomly
generated then you can verify file by its extension.
@BeforeClass
public void Setup() throws Exception
{
driver = new FirefoxDriver(ffprofile());
File directory = new File(FIleDownloadPath);
delete(directory); //create a function delete with code to delete directory and its files
}
//Method
where user will download a file and then verify
@Test
public void DownloadAndVerify()
{
driver.get(URL);
//Go to the place where link / button is placed for download
// Click on it to download file
Assert.assertTrue(VerifyFileDownloadWithName (FIleDownloadPath, "Name of file with extension"), "Failed to download Expected document");
//if file name is random then you can verify by extension
Assert.assertTrue(VerifyFileDownloadWithExtension (FIleDownloadPath, ".extension of file"), "Failed to download document which has extension ".extension of file ");
}
//To set
download functionality, with this download pop-up will not appeared
public static FirefoxProfile ffprofile() throws Exception
{
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir",downloadPath);
firefoxProfile.setPreference "browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/x-msexcel,application/excel,application/x-excel," +
"application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/" +
"msword,application/xml"
return firefoxProfile;
}
//Verify
file downloaded by its Name
public boolean VerifyFileDownloadWithName (String FIleDownloadPath, String fileName)
{
boolean flag = false;
File dir = new File(FIleDownloadPath);
File[] dir_contents = dir.listFiles();
for (int i = 0; i < dir_contents.length; i++)
{
if (dir_contents[i].getName().equals(fileName))
return flag=true;
}
return flag;
}
//Verify
file downloaded by its Extension
private boolean VerifyFileDownloadWithExtension(String FIleDownloadPath, String ext)
{
boolean flag=false;
File dir = new File(FIleDownloadPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0)
{
flag = false;
}
for (int i = 1; i < files.length; i++)
{
if(files[i].getName().contains(ext))
{
flag=true;
}
} return flag;
}
With this
code, hope you are set to handle Download Functionality.
Great Article… I love to read your articles because your writing style is too good, it is very very helpful for all of us and I never get bored while reading your article because they are becomes a more and more interesting from the starting lines until the end.
ReplyDeleteSelenium Training in Chennai