File download handling in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; import java.time.Duration; public class FileDownloadTest { private static final String DOWNLOAD_PATH = System.getProperty("user.home") + "/Downloads/"; private static final String FILE_NAME = "samplefile.txt"; public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("https://example.com/download"); // Wait for download button to be clickable WebElement downloadButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("downloadBtn"))); // Delete file if already exists to avoid false positive File file = new File(DOWNLOAD_PATH + FILE_NAME); if (file.exists()) { file.delete(); } // Click the download button downloadButton.click(); // Wait for the file to appear in the download folder boolean isDownloaded = waitForFileToExist(file, 15); // Assertion if (isDownloaded) { System.out.println("Test Passed: File downloaded successfully."); } else { System.out.println("Test Failed: File not found after download."); } // Clean up downloaded file if (file.exists()) { file.delete(); } } finally { driver.quit(); } } private static boolean waitForFileToExist(File file, int timeoutSeconds) { int waited = 0; while (waited < timeoutSeconds) { if (file.exists()) { return true; } try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } waited++; } return false; } }
This test script uses Selenium WebDriver with Java to automate the file download verification.
First, it opens the browser and navigates to the download page URL.
It waits explicitly for the download button to be clickable using WebDriverWait and ExpectedConditions.
Before clicking, it deletes any existing file with the same name in the download folder to avoid false positives.
After clicking the download button, it waits up to 15 seconds for the file to appear in the download folder by checking file existence every second.
If the file is found, it prints a pass message; otherwise, a fail message.
Finally, it cleans up by deleting the downloaded file and closes the browser.
This approach uses explicit waits for UI elements and Java File API for file verification, following best practices for maintainable and reliable tests.
Now add data-driven testing with 3 different file download buttons and expected file names
Practice
Solution
Step 1: Understand file download handling
File download handling in Selenium is used to check if files are saved correctly during automated tests.Step 2: Identify the correct purpose
Among the options, only verifying file downloads matches this purpose.Final Answer:
To verify that files are downloaded correctly without manual intervention -> Option AQuick Check:
File download handling = verify downloads [OK]
- Confusing download handling with file upload
- Thinking it changes browser settings unrelated to downloads
- Assuming it clears cookies automatically
Solution
Step 1: Identify how to set download folder in ChromeOptions
Setting the "download.default_directory" preference in ChromeOptions disables popup and sets download path.Step 2: Match code snippet with correct setting
ChromeOptions options = new ChromeOptions(); Map prefs = new HashMap<>(); prefs.put("download.default_directory", "/path/to/download"); options.setExperimentalOption("prefs", prefs); correctly creates prefs map and sets it as experimental option for ChromeOptions.Final Answer:
ChromeOptions options = new ChromeOptions(); Map prefs = new HashMap<>(); prefs.put("download.default_directory", "/path/to/download"); options.setExperimentalOption("prefs", prefs); -> Option CQuick Check:
Set prefs for download folder = ChromeOptions options = new ChromeOptions(); Map prefs = new HashMap<>(); prefs.put("download.default_directory", "/path/to/download"); options.setExperimentalOption("prefs", prefs); [OK]
- Using addArguments instead of prefs for download folder
- Setting headless mode does not affect downloads
- Forgetting to set experimental options
File file = new File("/downloads/report.pdf");
boolean isDownloaded = file.exists();
System.out.println(isDownloaded);Solution
Step 1: Understand file.exists() method
The exists() method returns true if the file exists at the given path, false otherwise.Step 2: Analyze the scenario
If the file "report.pdf" is downloaded successfully to "/downloads", file.exists() returns true and prints it.Final Answer:
true -> Option DQuick Check:
file.exists() = true if file present [OK]
- Assuming file.exists() throws exception if file missing
- Confusing boolean output with exceptions
- Thinking it returns file content
File file = new File("/downloads/report.pdf");
assertTrue(file.exists());
Options:Solution
Step 1: Identify timing issue in file existence check
The test may check file existence before download finishes, causing false failure.Step 2: Understand need for wait or polling
Adding wait or retry logic ensures file is fully downloaded before assertion.Final Answer:
The test does not wait for the download to complete before checking -> Option AQuick Check:
Wait for download before assertTrue(file.exists()) [OK]
- Assuming file path syntax is wrong
- Thinking assertTrue is invalid
- Believing File class can't check existence
Solution
Step 1: Configure browser for automatic downloads
Setting browser preferences to auto-download files avoids popup interruptions for all file types.Step 2: Verify download by checking folder for new file with expected extension
After triggering download, checking the folder for a new file with the correct extension confirms success reliably.Final Answer:
Set browser to download automatically, then check folder for new file with expected extension after triggering download -> Option BQuick Check:
Auto-download + check file extension = reliable verification [OK]
- Relying on manual popup handling in automated tests
- Using fixed sleep without checking file presence
- Ignoring file extension verification
Ready to prove it?
Pass the test and this pattern moves unknown
