Test Overview
This test automates downloading a file from a web page and verifies that the file is successfully saved in the expected folder.
This test automates downloading a file from a web page and verifies that the file is successfully saved in the expected folder.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.io.File; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertTrue; public class FileDownloadTest { public static void main(String[] args) throws InterruptedException { String downloadFilepath = System.getProperty("user.dir") + "/downloads"; File downloadDir = new File(downloadFilepath); if (!downloadDir.exists()) { downloadDir.mkdir(); } ChromeOptions options = new ChromeOptions(); options.addArguments("--headless=new"); options.addArguments("--disable-gpu"); options.addArguments("--window-size=1920,1080"); options.addArguments("--no-sandbox"); options.addArguments("--disable-dev-shm-usage"); options.setExperimentalOption("prefs", java.util.Map.of( "download.default_directory", downloadFilepath, "download.prompt_for_download", false, "download.directory_upgrade", true, "safebrowsing.enabled", true )); WebDriver driver = new ChromeDriver(options); try { driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); driver.get("https://www.selenium.dev/downloads/"); // Find the download link for Selenium Server (example file) driver.findElement(By.linkText("4.12.0")) .click(); // Wait for the file to appear in the download folder File downloadedFile = new File(downloadFilepath + "/selenium-server-4.12.0.jar"); int waitTime = 0; while (!downloadedFile.exists() && waitTime < 15000) { // wait max 15 seconds Thread.sleep(500); waitTime += 500; } assertTrue(downloadedFile.exists(), "Downloaded file should exist"); } finally { driver.quit(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and ChromeDriver is initialized with download preferences set to a custom folder | Browser is ready with headless mode and download folder configured | - | PASS |
| 2 | Browser navigates to https://www.selenium.dev/downloads/ | Selenium downloads page is loaded | - | PASS |
| 3 | Finds the link with text '4.12.0' and clicks it to start file download | Download of selenium-server-4.12.0.jar file starts | - | PASS |
| 4 | Waits up to 15 seconds for the file selenium-server-4.12.0.jar to appear in the download folder | File appears in the download folder | Check if downloaded file exists in the folder | PASS |
| 5 | Test ends and browser closes | Browser closed, test complete | - | PASS |