0
0
Selenium Javatesting~15 mins

File download handling in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Verify file download functionality on the sample download page
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com/download'
Step 2: Locate the download button with id 'downloadBtn'
Step 3: Click the download button
Step 4: Wait for the file to be downloaded completely in the default download folder
✅ Expected Result: The file named 'samplefile.txt' is downloaded successfully to the default download folder
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the file 'samplefile.txt' exists in the download folder after clicking the download button
Best Practices:
Use explicit waits to wait for the download button to be clickable
Use Java File API to check file existence
Clean up downloaded files after test to keep environment clean
Use Page Object Model to separate page interactions
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() to wait for the download button instead of explicit waits
{'mistake': 'Hardcoding the download folder path instead of using system properties', 'why_bad': 'Hardcoded paths may not work on different machines or OS, reducing test portability.', 'correct_approach': 'Use System.getProperty("user.home") to build the download path dynamically.'}
Not cleaning up downloaded files after test execution
Not verifying the file name or just checking download folder is not empty
Bonus Challenge

Now add data-driven testing with 3 different file download buttons and expected file names

Show Hint