0
0
Selenium Javatesting~10 mins

File upload (sendKeys to input) in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test automates uploading a file by sending the file path to a file input element. It verifies that the file input contains the correct file path after upload.

Test Code - JUnit with Selenium WebDriver
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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class FileUploadTest {
    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }

    @Test
    public void testFileUpload() {
        driver.get("https://example.com/upload");
        WebElement fileInput = driver.findElement(By.id("file-upload"));
        String filePath = System.getProperty("user.dir") + "/src/test/resources/sample.txt";
        fileInput.sendKeys(filePath);
        String uploadedFileName = fileInput.getAttribute("value");
        assertTrue(uploadedFileName.contains("sample.txt"), "Uploaded file name should contain 'sample.txt'");
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsTest framework initializes and prepares to run the test-PASS
2Browser opens Chrome and maximizes windowChrome browser window is open and maximized-PASS
3Navigates to 'https://example.com/upload'Upload page is loaded with a file input element having id 'file-upload'-PASS
4Finds file input element by id 'file-upload'File input element is located on the page-PASS
5Sends file path to file input element using sendKeysFile input element now contains the file path string-PASS
6Retrieves the value attribute of the file input elementValue attribute contains the uploaded file pathCheck that the value contains 'sample.txt'PASS
7Assertion checks if uploaded file name contains 'sample.txt'Assertion verifies the file input valueassertTrue(uploadedFileName.contains("sample.txt"))PASS
8Test ends and browser closesBrowser is closed and resources are cleaned up-PASS
Failure Scenario
Failing Condition: File input element with id 'file-upload' is not found or file path is incorrect
Execution Trace Quiz - 3 Questions
Test your understanding
What Selenium method is used to upload a file in this test?
AsendKeys
Bclick
Csubmit
DgetText
Key Result
Always verify the locator for the file input element is correct and the file path used in sendKeys is valid and accessible on the test machine.