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