Member-only story
How to check if a file got downloaded in java selenium tests
How to check a file exists in system:
//we use import java.io.File;
File f = new File("D:\\program.txt");
f.exists(); // this will print true or false whether the file program.txt exists
We can use this logic to check if the file got downloaded and is available at the location.
But sometimes we need to click download button and wait for like few mins or seconds for the download to finish.
so in this case we need to poll for the file till it exists . We might need to try polling for a max of 5 mins then fail the tests if file doesn’t exists
This can be achieved using custom expected condition:
Custom expected condition:
Define below expected class in any of your page object class
public ExpectedCondition<Boolean> filepresent() {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
File f = new File("D:\\program.txt");
return f.exists();
} @Override
public String toString() {
return String.format("file to be present within the time specified");
}
};
}
And call it inside text as :
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(2));
wait.until(pageobject.filepresent());
Output:
Failed:
Passed: