πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 42 of 100
File Upload/Download
Advanced

Verifying if File Download has Completed

πŸ“₯Scenario Overview

Verifying if File Download has Completed

Key Takeaways & Cheat Sheet

  • βœ“Create a dedicated dynamic download directory folder for testing
  • βœ“Configure browser profile options to save files to the target folder
  • βœ“Implement a loop checking for file existence in the directory
  • βœ“Ensure the file does not contain temporary extensions (like .crdownload)

Short Direct Answer

To verify file downloads, configure your browser profile to save downloads to a dedicated test folder. Write a dynamic wait loop that periodically checks the folder. The download is complete when the target file exists and does not have a temporary downloading extension (like `.crdownload` in Chrome or `.part` in Firefox).

⚠️ Senior Warning (Red Flag)

Never write a static sleep to "wait" for a download. Large files or slow network speeds will cause dynamic timing failures, resulting in flaky tests.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Always clean the target download folder before triggering a new download to prevent matches against stale historic test runs.

SeleniumAutomation.java
Selenium 4 + Java
import java.io.File;
import java.nio.file.Paths;

// βœ… Dynamic download check method
public boolean isFileDownloaded(String downloadFolderPath, String fileName, int timeoutSec) {
    File folder = new File(downloadFolderPath);
    long endTIme = System.currentTimeMillis() + (timeoutSec * 1000L);
    
    while (System.currentTimeMillis() < endTIme) {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.getName().equals(fileName) && !file.getName().endsWith(".crdownload")) {
                    return true; // File downloaded successfully
                }
            }
        }
        try { Thread.sleep(500); } catch (InterruptedException e) {}
    }
    return false; // Download timed out
}