Reputation: 8710
I have to test a web application using Selenium. The application has a link for downloading a file. I've set a Firefox profile so that the browser is downloading the file without asking for confirmation. My (simplified) Java code is as follows:
File file = new File("myPath");
driver.findElement(By.id("file-link-download-")).click(); // the download start here
// my test
if(!file.exists()) fail("file does not exist");
My problem is that the download runs in another thread and when "my test" (if file.exists()) is performed the file is not yet downloaded. I can pack this in a method putting some delay, like this:
public boolean fileExists(File file) {
try {// Just wait 1000 milliseconds to see if the file exists
Thread.sleep(sleep);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (file.exists()) {
return true;
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
return false;
}
But this is not nice and not enough. I think that the best way should be to have a separate thread with a timeout which watches if the file is already downloaded and then returns true or returns false if the timeout is there.
Which is the best way (the correct way) to deal with this problem?
Thanks!
Upvotes: 3
Views: 1969
Reputation: 25056
The FluentWait
class is designed for conditions like this. I noticed that you were just, essentially, attempting to duplicate what had already been done in this class.
Below is the source of it:
It's very generic, and therefore can handle all kinds of different conditions - yours included.
All you'd need to do is just check file.exists()
within the apply
method, as shown within the sample documentation:
http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html
Upvotes: 2