Popular Searches
Popular Course Categories
Popular Courses

File Download

Advanced Selenium

File Download in Selenium WebDriver

File Download is an important Selenium WebDriver concept used to automate the process of downloading files from web applications. In real-world web applications, users may download PDFs, Excel files, CSV reports, images, invoices, documents, certificates, and other files.

Selenium WebDriver can interact with download buttons and links, but it does not directly provide a dedicated API for controlling the operating system's native download dialog. Therefore, automated file downloads are generally handled by configuring the browser's download preferences before starting the WebDriver session.

File download automation is commonly used in Selenium frameworks for validating reports, invoices, export functionality, generated documents, CSV files, Excel files, PDF files, and other downloadable resources.

Course Resource: Selenium Training | Register for Course Demo


1. What is File Download?

File download is the process of retrieving a file from a web server and storing it on the user's local computer or a configured download directory.

For example, a web application may provide buttons such as:

  • Download PDF
  • Download Invoice
  • Export to Excel
  • Download CSV
  • Download Report
  • Download Certificate
  • Download Image
  • Download Document

During automation, Selenium can click the download element and the browser can save the file automatically to a predefined location.


2. Why is File Download Automation Important?

File download testing is important because many business applications generate documents and reports that users must be able to download correctly.

  • Verifies that the download button works correctly.
  • Confirms that the expected file is generated.
  • Validates downloaded file names.
  • Validates file extensions.
  • Checks whether the downloaded file exists.
  • Can verify file size.
  • Can validate downloaded file content.
  • Supports automated report testing.
  • Reduces repetitive manual download testing.
  • Can be integrated into regression testing.


3. File Download Automation Flow

Start Test

    |

    v

Launch Browser

    |

    v

Configure Download Directory

    |

    v

Open Application

    |

    v

Locate Download Button

    |

    v

Click Download

    |

    v

Browser Downloads File

    |

    v

Wait for Download Completion

    |

    v

Check File Exists

    |

    v

Validate File

    |

    v

Delete Test File

    |

    v

Test Completed


4. Selenium and Browser Download Handling

Selenium WebDriver controls the browser, while the browser itself handles the actual file download process.

A common automation approach is:

  1. Create a download directory.
  2. Configure browser preferences.
  3. Start WebDriver.
  4. Open the web application.
  5. Click the download link or button.
  6. Wait for the file to appear.
  7. Verify the downloaded file.


5. Chrome Download Configuration

Chrome can be configured using ChromeOptions. Download preferences can specify where downloaded files should be stored.

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

 

import java.util.HashMap;

import java.util.Map;

 

public class ChromeDownloadExample {

 

    public static void main(String[] args) {

 

        String downloadPath = "C:\\Automation\\Downloads";

 

        Map<String, Object> preferences = new HashMap<>();

 

        preferences.put("download.default_directory", downloadPath);

        preferences.put("download.prompt_for_download", false);

        preferences.put("download.directory_upgrade", true);

        preferences.put("safebrowsing.enabled", true);

 

        ChromeOptions options = new ChromeOptions();

        options.setExperimentalOption("prefs", preferences);

 

        ChromeDriver driver = new ChromeDriver(options);

 

        driver.get("https://example.com");

 

        // Continue automation here

    }

}


6. Understanding Chrome Download Preferences

PreferencePurpose
download.default_directorySpecifies the default download location.
download.prompt_for_downloadControls whether Chrome prompts before downloading.
download.directory_upgradeAllows Chrome to use the configured directory.
safebrowsing.enabledEnables Safe Browsing support for downloads.


7. Setting a Custom Download Directory

It is recommended to use a dedicated download directory for automated tests rather than the user's normal Downloads folder.

String downloadPath = "C:\\Automation\\Downloads";

A project-specific directory makes it easier to identify files created by automation and prevents test files from being mixed with personal downloads.


8. Creating the Download Directory

The directory can be created programmatically using Java's Files API.

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

 

Path downloadPath = Paths.get("downloads");

 

Files.createDirectories(downloadPath);

This approach helps ensure that the required directory exists before the browser starts downloading files.


9. Clicking a Download Link

Once the browser has been configured, Selenium can locate and click the download element like any other web element.

driver.findElement(By.id("downloadButton")).click();

For a link:

driver.findElement(By.linkText("Download Report")).click();


10. Download Using CSS Selector

driver.findElement(

    By.cssSelector("button.download")

).click();

CSS selectors can be useful when the download element contains a stable class or attribute.


11. Download Using XPath

driver.findElement(

    By.xpath("//button[contains(text(),'Download')]")

).click();

XPath can be used when the download element does not have a convenient unique ID.


12. Complete Chrome File Download Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

 

import java.util.HashMap;

import java.util.Map;

 

public class FileDownloadTest {

 

    public static void main(String[] args) {

 

        String downloadPath = "C:\\Automation\\Downloads";

 

        Map<String, Object> preferences = new HashMap<>();

        preferences.put("download.default_directory", downloadPath);

        preferences.put("download.prompt_for_download", false);

        preferences.put("download.directory_upgrade", true);

        preferences.put("safebrowsing.enabled", true);

 

        ChromeOptions options = new ChromeOptions();

        options.setExperimentalOption("prefs", preferences);

 

        WebDriver driver = new ChromeDriver(options);

 

        driver.get("https://example.com/download");

 

        driver.findElement(

            By.id("downloadButton")

        ).click();

 

        driver.quit();

    }

}


13. Why Should We Avoid the Native Download Dialog?

The native operating-system download dialog is outside the normal DOM that Selenium controls. Selenium primarily interacts with elements inside the browser page.

Instead of automating the operating-system dialog, browser download preferences can be configured so that the browser automatically saves the file to the required location.


14. File Download Verification

Clicking a download button does not always prove that the download was successful. A robust automation test should verify that the expected file actually exists.

import java.io.File;

 

File file = new File(

    "C:\\Automation\\Downloads\\report.pdf"

);

 

if (file.exists()) {

    System.out.println("File downloaded successfully");

} else {

    System.out.println("File download failed");

}


15. Verifying File Existence with Assertion

TestNG assertions can be used to validate the downloaded file.

import org.testng.Assert;

 

File file = new File(

    "C:\\Automation\\Downloads\\report.pdf"

);

 

Assert.assertTrue(

    file.exists(),

    "Downloaded file was not found"

);


16. Checking File Size

A file can exist but still be incomplete or empty. Therefore, checking file size can provide an additional validation.

long fileSize = file.length();

 

System.out.println(

    "File size: " + fileSize + " bytes"

);

 

Assert.assertTrue(

    fileSize > 0,

    "Downloaded file is empty"

);


17. Checking File Extension

The extension can be validated when the application is expected to download a specific file type.

String fileName = file.getName();

 

Assert.assertTrue(

    fileName.endsWith(".pdf"),

    "Expected a PDF file"

);


18. Checking File Name

String expectedFileName = "report.pdf";

 

Assert.assertEquals(

    file.getName(),

    expectedFileName

);

File-name validation is useful when the application generates predictable document names.


19. Waiting for a Download to Complete

Downloads may take time depending on file size, network speed, server response, and browser performance. Immediately checking for the file can therefore cause false failures.

A robust framework should wait until the expected file appears.

import java.io.File;

 

File file = new File(

    "C:\\Automation\\Downloads\\report.pdf"

);

 

int maxWait = 30;

 

for (int i = 0; i < maxWait; i++) {

 

    if (file.exists() && file.length() > 0) {

        break;

    }

 

    Thread.sleep(1000);

}


20. Better Download Wait Strategy

Instead of using a fixed long sleep, a polling mechanism can repeatedly check whether the file has appeared and stop as soon as the condition is satisfied.

public static boolean waitForFile(

        String filePath,

        int timeoutSeconds) throws InterruptedException {

 

    File file = new File(filePath);

 

    for (int i = 0; i < timeoutSeconds; i++) {

 

        if (file.exists() && file.length() > 0) {

            return true;

        }

 

        Thread.sleep(1000);

    }

 

    return false;

}


21. Handling Temporary Download Files

Browsers may create temporary files while a download is in progress. With Chromium-based browsers, a partially downloaded file may use a temporary extension such as .crdownload.

The automation framework should avoid treating a temporary file as a completed download.

File[] files = new File(

    "C:\\Automation\\Downloads"

).listFiles();

 

for (File file : files) {

 

    if (file.getName().endsWith(".crdownload")) {

        System.out.println(

            "Download still in progress: "

            + file.getName()

        );

    }

}


22. Checking for Completed Downloads

A useful strategy is to wait until the expected file exists and no temporary download file remains.

public static boolean isDownloadComplete(

        File directory,

        String expectedFileName) {

 

    File expectedFile = new File(

        directory,

        expectedFileName

    );

 

    if (!expectedFile.exists()) {

        return false;

    }

 

    File[] temporaryFiles = directory.listFiles(

        (dir, name) -> name.endsWith(".crdownload")

    );

 

    return temporaryFiles == null ||

           temporaryFiles.length == 0;

}


23. Downloading PDF Files

PDF files are commonly downloaded from reporting, billing, education, banking, and e-commerce applications.

driver.findElement(

    By.id("downloadPdf")

).click();

After the download, the test can verify that the PDF exists.

File pdf = new File(

    "C:\\Automation\\Downloads\\invoice.pdf"

);

 

Assert.assertTrue(

    pdf.exists(),

    "PDF was not downloaded"

);


24. Downloading Excel Files

Business applications frequently provide Excel exports for reports and data analysis.

driver.findElement(

    By.id("exportExcel")

).click();

The test can verify the downloaded Excel file:

File excelFile = new File(

    "C:\\Automation\\Downloads\\report.xlsx"

);

 

Assert.assertTrue(

    excelFile.exists(),

    "Excel file was not downloaded"

);


25. Downloading CSV Files

driver.findElement(

    By.id("exportCsv")

).click();

After downloading, the CSV file can be checked for existence and content.

File csvFile = new File(

    "C:\\Automation\\Downloads\\users.csv"

);

 

Assert.assertTrue(

    csvFile.exists(),

    "CSV file was not downloaded"

);


26. Downloading Image Files

Applications may allow users to download images, product photos, certificates, or generated graphics.

driver.findElement(

    By.id("downloadImage")

).click();

The downloaded file can then be verified using Java file APIs.


27. Firefox File Download Configuration

Firefox can also be configured for automatic downloads using FirefoxOptions.

import org.openqa.selenium.firefox.FirefoxOptions;

 

FirefoxOptions options = new FirefoxOptions();

 

options.addPreference(

    "browser.download.folderList", 2

);

 

options.addPreference(

    "browser.download.dir",

    "C:\\Automation\\Downloads"

);

 

options.addPreference(

    "browser.helperApps.neverAsk.saveToDisk",

    "application/pdf"

);

 

options.addPreference(

    "pdfjs.disabled",

    true

);


28. Firefox MIME Types

Firefox can use MIME types to determine which files should be downloaded automatically without displaying a prompt.

File TypeExample MIME Type
PDFapplication/pdf
CSVtext/csv
Excelapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
ZIPapplication/zip
JSONapplication/json


29. File Download with TestNG

File download testing can be integrated directly into a TestNG test class.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

import java.io.File;

import java.util.HashMap;

import java.util.Map;

 

public class FileDownloadTest {

 

    WebDriver driver;

 

    String downloadPath =

        "C:\\Automation\\Downloads";

 

    @BeforeMethod

    public void setup() {

 

        Map<String, Object> preferences =

            new HashMap<>();

 

        preferences.put(

            "download.default_directory",

            downloadPath

        );

 

        preferences.put(

            "download.prompt_for_download",

            false

        );

 

        ChromeOptions options =

            new ChromeOptions();

 

        options.setExperimentalOption(

            "prefs",

            preferences

        );

 

        driver = new ChromeDriver(options);

    }

 

    @Test

    public void downloadTest() {

 

        driver.get(

            "https://example.com/download"

        );

 

        driver.findElement(

            By.id("downloadButton")

        ).click();

 

        File file = new File(

            downloadPath + "\\report.pdf"

        );

 

        Assert.assertTrue(

            file.exists(),

            "File was not downloaded"

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


30. Cleaning the Download Directory

Old files can interfere with later test executions. Therefore, the download directory should often be cleaned before or after each test.

File directory = new File(

    "C:\\Automation\\Downloads"

);

 

File[] files = directory.listFiles();

 

if (files != null) {

    for (File file : files) {

        file.delete();

    }

}


31. Why Clean the Download Folder?

  • Prevents old files from being mistaken for newly downloaded files.
  • Improves test reliability.
  • Makes debugging easier.
  • Prevents unnecessary disk usage.
  • Keeps test execution isolated.
  • Makes file validation more accurate.


32. Download File with Dynamic File Names

Some applications generate file names dynamically.

For example:

Report_2026_10_01.pdf

Invoice_10025.pdf

UserReport_John.xlsx

In such situations, the test can search the download directory instead of checking for one exact file name.

File directory = new File(

    "C:\\Automation\\Downloads"

);

 

File[] files = directory.listFiles();

 

if (files != null) {

 

    for (File file : files) {

 

        if (file.getName().endsWith(".pdf")) {

            System.out.println(

                "PDF found: " + file.getName()

            );

        }

    }

}


33. Finding the Latest Downloaded File

When file names are dynamic, the latest modified file can be identified.

File directory = new File(

    "C:\\Automation\\Downloads"

);

 

File[] files = directory.listFiles();

 

File latestFile = null;

 

if (files != null) {

 

    for (File file : files) {

 

        if (latestFile == null ||

            file.lastModified() >

            latestFile.lastModified()) {

 

            latestFile = file;

        }

    }

}

 

if (latestFile != null) {

    System.out.println(

        "Latest file: " +

        latestFile.getName()

    );

}


34. Validating Downloaded PDF Content

Checking only whether a PDF exists may not be sufficient. In some testing scenarios, the content of the PDF must also be verified.

Java PDF libraries such as Apache PDFBox can be used to extract text from a PDF.

PDDocument document =

    PDDocument.load(file);

 

PDFTextStripper stripper =

    new PDFTextStripper();

 

String text = stripper.getText(document);

 

Assert.assertTrue(

    text.contains("Invoice")

);

 

document.close();

This type of validation should be used when the actual contents of the downloaded document are part of the test requirement.


35. Validating Excel Download

Apache POI can be used to read downloaded Excel files and verify worksheets, cells, headers, and values.

FileInputStream input =

    new FileInputStream(file);

 

Workbook workbook =

    WorkbookFactory.create(input);

 

Sheet sheet =

    workbook.getSheetAt(0);

 

String value =

    sheet.getRow(0)

         .getCell(0)

         .getStringCellValue();

 

System.out.println(value);

 

workbook.close();

input.close();


36. Validating CSV Download

CSV files can be read using Java file APIs or dedicated CSV libraries.

List<String> lines =

    Files.readAllLines(

        Paths.get("C:\\Automation\\Downloads\\users.csv")

    );

 

for (String line : lines) {

    System.out.println(line);

}


37. File Download and Page Object Model

In a Page Object Model framework, download-related elements and actions can be maintained inside a dedicated page class.

public class ReportPage {

 

    WebDriver driver;

 

    By downloadButton =

        By.id("downloadReport");

 

    public ReportPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void downloadReport() {

        driver.findElement(

            downloadButton

        ).click();

    }

}

The test class can then use the page object:

ReportPage reportPage =

    new ReportPage(driver);

 

reportPage.downloadReport();


38. POM-Based File Download Test

public class ReportDownloadTest {

 

    WebDriver driver;

    ReportPage reportPage;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.get(

            "https://example.com/reports"

        );

 

        reportPage =

            new ReportPage(driver);

    }

 

    @Test

    public void downloadReportTest() {

 

        reportPage.downloadReport();

 

        File file = new File(

            "C:\\Automation\\Downloads\\report.pdf"

        );

 

        Assert.assertTrue(

            file.exists()

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


39. File Download and Explicit Wait

Selenium's normal explicit waits are designed primarily for browser DOM conditions. File-system conditions can be handled through custom polling logic or a framework utility.

public static boolean waitForDownload(

        String filePath,

        int timeoutSeconds)

        throws InterruptedException {

 

    File file = new File(filePath);

 

    for (int i = 0;

         i < timeoutSeconds;

         i++) {

 

        if (file.exists() &&

            file.length() > 0) {

 

            return true;

        }

 

        Thread.sleep(1000);

    }

 

    return false;

}


40. File Download Utility Class

A reusable utility class can centralize download verification logic.

public class DownloadUtils {

 

    public static boolean isFileDownloaded(

            String directory,

            String fileName) {

 

        File file = new File(

            directory,

            fileName

        );

 

        return file.exists() &&

               file.length() > 0;

    }

 

    public static void deleteFile(

            String directory,

            String fileName) {

 

        File file = new File(

            directory,

            fileName

        );

 

        if (file.exists()) {

            file.delete();

        }

    }

}


41. Using the Download Utility

boolean downloaded =

    DownloadUtils.isFileDownloaded(

        "C:\\Automation\\Downloads",

        "report.pdf"

    );

 

Assert.assertTrue(

    downloaded,

    "Report was not downloaded"

);


42. File Download with Multiple Browsers

File download automation can be implemented for different browsers. The browser-specific configuration should be maintained in the driver factory or browser setup layer.

BrowserTypical Configuration
ChromeChromeOptions preferences
FirefoxFirefoxOptions preferences
EdgeEdgeOptions preferences


43. File Download with Edge

Microsoft Edge is Chromium-based and can be configured using EdgeOptions.

import org.openqa.selenium.edge.EdgeDriver;

import org.openqa.selenium.edge.EdgeOptions;

 

Map<String, Object> preferences =

    new HashMap<>();

 

preferences.put(

    "download.default_directory",

    "C:\\Automation\\Downloads"

);

 

preferences.put(

    "download.prompt_for_download",

    false

);

 

EdgeOptions options =

    new EdgeOptions();

 

options.setExperimentalOption(

    "prefs",

    preferences

);

 

WebDriver driver =

    new EdgeDriver(options);


44. File Download Using a Data Provider

TestNG Data Providers can be combined with file download tests when multiple documents, URLs, or expected file types need to be tested.

@DataProvider(name = "downloads")

public Object[][] downloads() {

 

    return new Object[][] {

        {"PDF", "report.pdf"},

        {"Excel", "report.xlsx"},

        {"CSV", "report.csv"}

    };

}

 

@Test(dataProvider = "downloads")

public void downloadTest(

        String type,

        String expectedFile) {

 

    System.out.println(

        "Testing: " + type

    );

 

    // Download logic

 

    System.out.println(

        "Expected: " + expectedFile

    );

}


45. File Download with Different URLs

When different download resources are tested, URLs can also be supplied through a Data Provider.

@DataProvider(name = "fileData")

public Object[][] fileData() {

 

    return new Object[][] {

        {

            "https://example.com/report.pdf",

            "report.pdf"

        },

        {

            "https://example.com/data.csv",

            "data.csv"

        }

    };

}

 

@Test(dataProvider = "fileData")

public void downloadTest(

        String url,

        String expectedFile) {

 

    driver.get(url);

 

    // Validate download

}


46. Common File Download Scenarios

ScenarioValidation
Download PDFCheck PDF exists and optionally validate content.
Download ExcelCheck XLS/XLSX exists and validate workbook data.
Download CSVCheck file exists and validate rows.
Download InvoiceValidate file name and invoice content.
Export ReportValidate generated report file.
Download CertificateValidate generated document.
Download ImageValidate file type and existence.


47. File Download vs File Upload

File DownloadFile Upload
Retrieves a file from the application.Sends a local file to the application.
Browser download preferences may be required.Usually uses sendKeys() with an input element.
Requires file-system validation.Requires upload validation.
Example: Download Report.Example: Upload Resume.


48. File Download vs Screenshot

File DownloadScreenshot
Downloads an application-generated or linked file.Captures the browser page or element.
Usually initiated by a download link/button.Usually created using TakesScreenshot.
Requires download directory handling.Requires screenshot path handling.


49. Common Mistakes in File Download Automation

  • Not configuring the download directory.
  • Checking the file immediately after clicking the download button.
  • Using a fixed sleep that is too short.
  • Using a fixed sleep that is unnecessarily long.
  • Not cleaning old files before the test.
  • Checking only file existence without checking completion.
  • Ignoring temporary download files.
  • Using a shared download directory for parallel tests.
  • Hard-coding operating-system-specific paths without considering the execution environment.
  • Not validating the downloaded file content when content validation is required.
  • Assuming the file name will always be static.
  • Not handling dynamic file names.


50. Best Practices for File Downloads

  • Use a dedicated download directory for automation.
  • Configure the browser before starting the test.
  • Clean old files before execution.
  • Wait for the download to complete.
  • Check both file existence and file size.
  • Handle dynamic file names carefully.
  • Validate file content when required.
  • Use reusable download utility methods.
  • Keep download configuration separate from test logic.
  • Use Page Object Model for download-page interactions.
  • Avoid shared download directories during parallel execution.
  • Use platform-independent path handling where practical.
  • Remove temporary test files after execution when appropriate.


51. File Paths and Cross-Platform Automation

Hard-coded Windows paths can cause problems when tests execute on Linux or CI servers.

Instead of:

String path =

    "C:\\Automation\\Downloads";

Use Java's path APIs where practical:

Path downloadPath =

    Paths.get(

        System.getProperty("user.dir"),

        "downloads"

    );

This approach makes the test framework easier to run across different environments.


52. File Download in CI/CD

File download tests can run in CI/CD environments such as Jenkins or other build servers. The framework should use a workspace-relative download directory rather than relying on a developer's local machine.

Project Workspace

       |

       v

Create Downloads Directory

       |

       v

Start Browser

       |

       v

Execute Selenium Test

       |

       v

Download File

       |

       v

Validate File

       |

       v

Archive Test Results

       |

       v

Clean Workspace


53. Headless Browser File Downloads

Automated test suites often execute browsers in headless mode in CI environments. Download configuration should still be explicitly configured and verified.

ChromeOptions options =

    new ChromeOptions();

 

options.addArguments("--headless=new");

 

Map<String, Object> preferences =

    new HashMap<>();

 

preferences.put(

    "download.default_directory",

    "downloads"

);

 

preferences.put(

    "download.prompt_for_download",

    false

);

 

options.setExperimentalOption(

    "prefs",

    preferences

);


54. File Download and Parallel Execution

When multiple tests run in parallel, using the same download directory can create conflicts. One test may accidentally validate a file created by another test.

A safer architecture is to provide separate directories for individual test executions or threads.

Parallel Test 1

    |

    +-- downloads/test1/

 

Parallel Test 2

    |

    +-- downloads/test2/

 

Parallel Test 3

    |

    +-- downloads/test3/


55. File Download and Reporting

Download validation can be included in TestNG reports. A failed test should clearly indicate whether the file was missing, empty, incorrectly named, or had invalid content.

Download Test

    |

    +-- Click Download

    |

    +-- File Found

    |

    +-- File Size Valid

    |

    +-- File Name Valid

    |

    +-- Content Valid

    |

    +-- PASS

Clear validation messages make troubleshooting much easier.


56. Practical Project Structure

src

|-- test

|   |-- java

|       |-- tests

|       |   |-- FileDownloadTest.java

|       |

|       |-- pages

|       |   |-- ReportPage.java

|       |   |-- InvoicePage.java

|       |

|       |-- utilities

|           |-- DownloadUtils.java

|           |-- DriverFactory.java

|           |-- FileReader.java

|           |-- ConfigReader.java

|

|-- downloads

|-- reports


57. Complete Practical File Download Framework

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.chrome.ChromeOptions;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

import java.io.File;

import java.util.HashMap;

import java.util.Map;

 

public class FileDownloadTest {

 

    WebDriver driver;

 

    String downloadPath =

        System.getProperty("user.dir")

        + File.separator

        + "downloads";

 

    @BeforeMethod

    public void setup() {

 

        File directory =

            new File(downloadPath);

 

        if (!directory.exists()) {

            directory.mkdirs();

        }

 

        Map<String, Object> preferences =

            new HashMap<>();

 

        preferences.put(

            "download.default_directory",

            downloadPath

        );

 

        preferences.put(

            "download.prompt_for_download",

            false

        );

 

        preferences.put(

            "download.directory_upgrade",

            true

        );

 

        preferences.put(

            "safebrowsing.enabled",

            true

        );

 

        ChromeOptions options =

            new ChromeOptions();

 

        options.setExperimentalOption(

            "prefs",

            preferences

        );

 

        driver =

            new ChromeDriver(options);

 

        driver.manage()

              .window()

              .maximize();

    }

 

    @Test

    public void downloadReportTest()

            throws InterruptedException {

 

        driver.get(

            "https://example.com/reports"

        );

 

        driver.findElement(

            By.id("downloadReport")

        ).click();

 

        File file = new File(

            downloadPath,

            "report.pdf"

        );

 

        boolean downloaded = false;

 

        for (int i = 0; i < 30; i++) {

 

            if (file.exists() &&

                file.length() > 0) {

 

                downloaded = true;

                break;

            }

 

            Thread.sleep(1000);

        }

 

        Assert.assertTrue(

            downloaded,

            "Report was not downloaded"

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


58. Real-World E-Commerce Example

Consider an e-commerce application where the user can download an invoice after completing an order.

Login

  |

  v

Search Product

  |

  v

Add Product to Cart

  |

  v

Checkout

  |

  v

Place Order

  |

  v

Open Order History

  |

  v

Click Download Invoice

  |

  v

Wait for Invoice

  |

  v

Verify Invoice PDF

  |

  v

Test Complete

The automation can verify that the invoice is generated, downloaded, and stored correctly.


59. Real-World Report Download Example

Business applications frequently provide reports for users. A typical automated report test can follow this process:

  1. Login to the application.
  2. Navigate to the Reports page.
  3. Select report filters.
  4. Click Generate Report.
  5. Click Download.
  6. Wait for the file.
  7. Verify the file exists.
  8. Verify the extension.
  9. Verify file size.
  10. Validate file content if required.
  11. Record the result in the test report.


60. File Download Architecture

Test Case

    |

    v

Page Object

    |

    v

Download Button

    |

    v

Browser

    |

    v

Download Directory

    |

    v

Download Utility

    |

    +-- File Exists

    |

    +-- File Size

    |

    +-- File Name

    |

    +-- File Extension

    |

    +-- File Content

    |

    v

Assertion

    |

    v

Test Report


61. Advantages of File Download Automation

  • Automation: Eliminates repetitive manual download verification.
  • Accuracy: Provides consistent validation.
  • Regression Support: Download functionality can be tested repeatedly.
  • Content Validation: Downloaded files can be inspected.
  • Cross-Browser Testing: Download behavior can be tested across supported browsers.
  • CI/CD Support: Download tests can execute automatically in pipelines.
  • Reusable Utilities: File validation logic can be reused across tests.


62. Limitations and Challenges

  • Browser download behavior can vary between browsers.
  • File downloads are asynchronous.
  • Dynamic file names require additional handling.
  • Large files may take significant time to download.
  • Parallel tests can cause download-directory conflicts.
  • CI environments may have different file-system paths.
  • Downloaded file content may require additional libraries to validate.
  • Some applications use authentication or expiring download URLs.


63. File Download vs Direct HTTP Download

Selenium is useful when the requirement is to verify the browser-based user workflow. In some situations, a direct HTTP client can be more efficient for downloading and validating a file from a known endpoint.

Selenium Browser DownloadDirect HTTP Download
Tests the user-facing browser workflow.Tests the HTTP resource directly.
Useful for verifying download buttons and links.Useful for API/resource-level validation.
Requires browser configuration.Does not require a browser.
Usually slower.Can be faster for direct resource validation.


64. Common Interview Questions on File Download

1. How do you handle file downloads in Selenium?

Configure the browser's download preferences before creating the WebDriver instance, click the download element, and then validate the downloaded file using Java file APIs.

2. Can Selenium directly control the operating-system download dialog?

Selenium primarily interacts with the browser DOM and does not provide a general API for native operating-system dialogs. Browser preferences are commonly used to avoid the dialog.

3. How do you set a custom download directory in Chrome?

Use ChromeOptions and set the download.default_directory preference.

4. How do you verify that a file was downloaded?

Use Java's File or NIO APIs to check whether the expected file exists.

5. Why should you wait after clicking Download?

File downloads are asynchronous, so the file may not be available immediately after the click.

6. How can you check whether a downloaded file is empty?

Use the file's length() method and verify that its size is greater than zero.

7. How can you handle dynamic file names?

Search the download directory for files matching the expected extension or naming pattern.

8. How can you validate a downloaded PDF?

First verify the file exists, then use a PDF library such as Apache PDFBox when content validation is required.

9. How can you validate an Excel download?

Apache POI can be used to open the workbook and validate sheets, rows, cells, and values.

10. What is a .crdownload file?

It is a temporary file extension commonly associated with an in-progress Chromium-based browser download.

11. Why should old downloaded files be deleted?

Old files can cause false positives because a test might detect a previous file instead of the file generated by the current test.

12. Can file downloads be tested in headless mode?

Yes, but the browser should be configured correctly and the downloaded file should be verified.

13. How do you handle downloads in parallel tests?

Use isolated download directories or otherwise ensure that concurrent tests cannot interfere with each other's downloaded files.

14. Can Data Providers be used with file download tests?

Yes. A Data Provider can supply multiple URLs, file types, expected names, or download scenarios.

15. Why use a download utility class?

A utility class centralizes reusable operations such as waiting for files, checking existence, checking size, and deleting files.


65. Quick Reference Table

ConceptDescription
ChromeOptionsConfigures Chrome before WebDriver starts.
download.default_directorySets the browser download location.
download.prompt_for_downloadControls the download prompt.
File.exists()Checks whether a file exists.
File.length()Returns the file size.
File.getName()Returns the file name.
Files.createDirectories()Creates a directory if required.
FirefoxOptionsConfigures Firefox download behavior.
EdgeOptionsConfigures Edge download behavior.
Download UtilityCentralizes reusable file validation logic.
Page Object ModelSeparates page interactions from test logic.


66. Learning Roadmap for File Download

  1. Understand Selenium WebDriver browser configuration.
  2. Learn ChromeOptions and FirefoxOptions.
  3. Configure a custom download directory.
  4. Automate a download button.
  5. Verify file existence.
  6. Verify file size.
  7. Validate file name and extension.
  8. Wait for asynchronous downloads.
  9. Handle temporary download files.
  10. Handle dynamic file names.
  11. Validate PDF files.
  12. Validate Excel and CSV files.
  13. Create reusable download utilities.
  14. Integrate downloads with Page Object Model.
  15. Handle downloads in parallel execution.
  16. Run file download tests in CI/CD.


67. Practical Exercises

  1. Configure Chrome to automatically download files to a custom directory.
  2. Automate a PDF download button.
  3. Verify that the downloaded PDF exists.
  4. Verify that the PDF is not empty.
  5. Verify the downloaded file extension.
  6. Automate an Excel report download.
  7. Automate a CSV export.
  8. Create a utility method to wait for a downloaded file.
  9. Create a utility method to delete downloaded files.
  10. Handle a dynamically generated file name.
  11. Validate PDF content using PDFBox.
  12. Validate Excel content using Apache POI.
  13. Execute download tests using TestNG.
  14. Execute download tests using a Data Provider.
  15. Integrate file downloads into a Page Object Model framework.
  16. Execute file download tests in a CI/CD environment.


68. Real-World Practical Scenario

Suppose an employee management application provides an option to download an employee report in Excel format.

Login

  |

  v

Employee Dashboard

  |

  v

Reports

  |

  v

Select Employee Filter

  |

  v

Generate Report

  |

  v

Click Download Excel

  |

  v

Wait for File

  |

  v

Verify .xlsx File

  |

  v

Open Workbook

  |

  v

Validate Header

  |

  v

Validate Employee Data

  |

  v

PASS

This scenario combines Selenium browser automation, file-system validation, TestNG assertions, and external file-reading libraries.


69. Summary

File Download automation is an important Selenium WebDriver skill for testing applications that generate or provide downloadable resources. Selenium can click the download element, while browser configuration controls how the file is saved.

A reliable file download test should configure a dedicated download directory, trigger the download, wait for completion, verify the file exists, check its size, validate its name or extension, and inspect the content when required.

For larger Selenium frameworks, file download functionality can be combined with TestNG, Page Object Model, Data Providers, reusable utility classes, PDF/Excel readers, reporting, parallel execution, and CI/CD pipelines.

The overall workflow can be summarized as:

Configure Browser

      |

      v

Set Download Directory

      |

      v

Open Application

      |

      v

Click Download

      |

      v

Wait for Completion

      |

      v

Verify File

      |

      v

Validate File

      |

      v

Report Result


70. Course Resources

Learn more about Selenium WebDriver, TestNG, Page Object Model, file handling, automation frameworks, and related software testing concepts through the Selenium training resources:

Final Takeaway: Selenium file download automation allows testers to verify that web applications correctly generate and download files. By combining browser download configuration with Java file handling, TestNG assertions, reusable utilities, and content validation libraries, download functionality can become a reliable part of a professional Selenium automation framework.

whatsapp