File Upload in Playwright



File Upload in Playwright Java – Complete Step-by-Step Guide (With Examples)

Automating file upload functionality is one of the most important use cases in web test automation. Many modern web applications require users to upload documents, images, PDFs, spreadsheets, or other files. If you are working with Playwright Java, understanding how file upload works will help you build stable and reliable automation scripts.

In this comprehensive guide, you will learn:

  • What file upload means in Playwright

  • How browsers handle file inputs

  • Why automation tools cannot use native file picker dialogs

  • How to upload single and multiple files in Playwright Java

  • How to clear uploaded files

  • Best practices for handling file uploads in automation

  • A complete working Java example

This article is fully SEO optimized and written in a human-friendly way so both beginners and experienced automation testers can understand it clearly.


What Is File Upload in Playwright?

In Playwright, file upload refers to automating the process of selecting and submitting files through an HTML file input element:

<input type="file">

Normally, when a user clicks the “Choose File” button on a website, a native file picker dialog opens. The user then selects a file from their local system. However, automation tools like Playwright cannot directly interact with the operating system’s file picker window, because it is outside the browser’s DOM (Document Object Model).

Instead of interacting with the OS-level dialog, Playwright bypasses it entirely by directly assigning file paths to the <input type="file"> element in the DOM.

This approach makes file upload automation:

  • Faster

  • More stable

  • Independent of OS-level UI

  • Cross-platform compatible


How Playwright Handles File Upload

Playwright provides the setInputFiles() method to simulate file upload.

In Playwright Java, this method is used with a locator that identifies the <input type="file"> element.

Why Playwright Avoids the File Picker Dialog

The file picker dialog is:

  • Controlled by the operating system

  • Outside browser control

  • Not part of the webpage DOM

Because Playwright operates inside the browser context, it cannot access OS-level components. Therefore, it programmatically attaches the file directly to the input field.

This ensures:

  • Better automation reliability

  • No dependency on UI dialogs

  • Faster test execution


Key Concepts of File Upload in Playwright Java

Before jumping into the code, let’s understand the theory behind file upload automation.

1. File Input Element

File uploads only work with:

<input type="file">

Browsers restrict file access for security reasons. You cannot upload files to other types of input fields.


2. Bypassing the Native File Dialog

Instead of clicking and selecting files manually, Playwright directly assigns file paths to the input element.

This eliminates:

  • Dialog handling complexity

  • OS compatibility issues

  • Unnecessary waits


3. Uploading Single File

You can upload one file using:

locator.setInputFiles(Paths.get("file.txt"));


4. Uploading Multiple Files

If the input field contains the multiple attribute:

<input type="file" multiple>

You can upload multiple files:

locator.setInputFiles(new Path[]{ Paths.get("file1.txt"), Paths.get("file2.txt") });


5. Clearing Uploaded Files

Just like a user can remove a selected file, Playwright can also clear the file input:

locator.setInputFiles(new Path[]{});

This resets the input field.


6. Security Model

Browsers do not allow arbitrary file access for security reasons.

Playwright complies with browser security by:

  • Uploading only explicitly specified files

  • Requiring full file paths

  • Preventing background system file access


Steps to Upload a File in Playwright Java

Here is the step-by-step process:

  1. Launch the browser

  2. Navigate to the webpage

  3. Locate the <input type="file"> element

  4. Use setInputFiles()

  5. Submit the form (if required)

  6. Validate upload success


Example Website for File Upload

We will use this demo website:

https://the-internet.herokuapp.com/upload

This page contains:

  • A file upload input field

  • An upload button

  • A success confirmation message


Maven Dependency for Playwright Java

Add this dependency in your pom.xml:

<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.43.0</version> </dependency>

Always use the latest version for best performance and bug fixes.


Complete File Upload Example in Playwright Java

Here is a fully working Java program:

import com.microsoft.playwright.*; import java.nio.file.Paths; public class FileUploadExample { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); Page page = browser.newPage(); // Navigate to file upload page page.navigate("https://the-internet.herokuapp.com/upload"); // Upload file page.locator("input#file-upload") .setInputFiles(Paths.get("example.txt")); // Click upload button page.locator("input#file-submit").click(); // Capture success message String uploadedMessage = page.locator("h3").textContent(); System.out.println("Upload Result: " + uploadedMessage); } } }


Explanation of the Code

1. Playwright Initialization

Playwright playwright = Playwright.create();

Initializes Playwright engine.


2. Launch Browser

playwright.chromium().launch(...)

Launches Chromium browser in non-headless mode so you can see execution.


3. Navigate to Page

page.navigate("https://the-internet.herokuapp.com/upload");

Opens the upload page.


4. Upload File

page.locator("input#file-upload") .setInputFiles(Paths.get("example.txt"));

This directly attaches example.txt to the file input element.


5. Submit Form

page.locator("input#file-submit").click();

Clicks the Upload button.


6. Verify Result

page.locator("h3").textContent();

Captures confirmation message and prints it.


Upload Multiple Files in Playwright Java

If the input supports multiple files:

page.locator("input[type='file']") .setInputFiles(new java.nio.file.Path[]{ Paths.get("file1.txt"), Paths.get("file2.txt") });

This uploads both files in a single action.


Upload File Using FilePayload (Advanced Usage)

Playwright also allows uploading file content dynamically using FilePayload.

Example:

byte[] fileContent = "Hello Playwright".getBytes(); FilePayload payload = new FilePayload( "sample.txt", "text/plain", fileContent ); page.locator("input[type='file']").setInputFiles(payload);

This is useful when:

  • Generating files dynamically

  • Avoiding physical file storage

  • Testing edge cases


Best Practices for File Upload Automation

To ensure reliable automation, follow these best practices:

1. Always Use Absolute Path (Recommended)

Paths.get("C:/Users/YourName/Documents/example.txt");

Avoid relative paths in CI/CD environments.


2. Validate Upload Success

Always verify confirmation messages or UI changes after upload.


3. Handle Waits Properly

Playwright auto-waits for elements, but ensure the page is fully loaded before interacting.


4. Use Assertions

Combine with JUnit or TestNG to validate:

  • File name displayed

  • Success message

  • Server response


5. Clean Up Test Files

Remove temporary files after test execution if needed.


Common Interview Questions on Playwright File Upload

Q1: Why can't automation tools interact with file picker dialogs?

Because they belong to the operating system and are outside browser DOM.


Q2: Which method is used to upload files in Playwright Java?

setInputFiles()


Q3: Can Playwright upload multiple files?

Yes, if the input supports the multiple attribute.


Q4: Can we clear uploaded files?

Yes, by passing an empty array to setInputFiles().


Advantages of Using Playwright for File Upload

  • Cross-browser support (Chromium, Firefox, WebKit)

  • Fast execution

  • Built-in auto waiting

  • Reliable element handling

  • CI/CD friendly


Real-World Use Cases

File upload automation is commonly used in:

  • Resume upload in job portals

  • Profile picture upload

  • Document submission forms

  • Invoice or receipt upload systems

  • Bulk data import features


Troubleshooting Common Issues

File Not Found Error

Ensure the file path exists on your machine.


Element Not Found

Verify correct CSS selector or XPath.


Upload Not Triggering

Ensure you are targeting the correct <input type="file"> element, not a styled button.


Conclusion

File upload automation in Playwright Java is simple, powerful, and highly reliable. Instead of dealing with complicated OS-level dialogs, Playwright directly attaches files to input elements using the setInputFiles() method.

In this guide, we covered:

  • What file upload means in Playwright

  • How browsers handle file inputs

  • Why native dialogs are bypassed

  • Single and multiple file uploads

  • Clearing file inputs

  • Complete working Java examples

  • Best practices and troubleshooting

Mastering file upload automation will significantly improve your test coverage and help you handle real-world application scenarios effectively.

If you are learning Playwright Java automation, this is an essential concept you must practice.


Playwright with Junit


















Complete Guide to Assertions in Playwright Java with JUnit (SEO Optimized & AdSense Friendly)

When building automated UI tests, performing actions like clicking buttons or filling forms is only half the job. The real value of automation comes from validating expected outcomes. That’s where assertions play a critical role.

In Playwright for Java, assertions help verify conditions such as whether an element is visible, enabled, contains specific text, or whether a page title matches the expected value. Without assertions, automation scripts cannot truly confirm that an application behaves correctly.

In this detailed and beginner-friendly guide, we will explore:

  • What are assertions in Playwright Java?

  • How Playwright and JUnit work together

  • Benefits of using Playwright with JUnit

  • Common assertion types in Playwright

  • Complete login page example with JUnit

  • Maven dependencies setup

  • Code explanation in detail

  • Best practices for writing stable assertions

  • Real-world testing tips

This guide is written in a human-like style, fully SEO optimized, and AdSense-friendly for educational publishing.


What Are Assertions in Playwright Java?

Assertions are validation statements used in automated tests to verify whether a condition is true.

For example:

  • Is the login button visible?

  • Does the page title contain the expected text?

  • Is an input field enabled?

  • Does an element contain specific text?

If the assertion passes, the test continues.
If it fails, the test stops and reports an error.

In Playwright for Java, assertions can be performed using:

  1. JUnit assertions

  2. TestNG assertions

  3. Playwright’s built-in Assertions class

Playwright provides a powerful assertion library under:

com.microsoft.playwright.assertions


How Playwright and JUnit Work Together

Playwright is responsible for:

  • Launching browsers

  • Navigating web pages

  • Interacting with UI elements

JUnit provides:

  • Test structure

  • Assertions

  • Lifecycle management

  • Reporting

In simple terms:

👉 Playwright performs browser automation
👉 JUnit manages and validates test execution

Each test method in JUnit represents a test scenario such as:

  • Login functionality

  • Form submission

  • Navigation verification

  • UI validation

Inside these test methods, Playwright is used to interact with the application.


Benefits of Using Playwright with JUnit

Using Playwright with JUnit offers several advantages.


(a) Organized Test Execution

JUnit allows grouping tests into classes and methods.

Example:

  • LoginTest

  • RegistrationTest

  • DashboardTest

Tests can be run:

  • Individually

  • As a suite

  • From Maven

  • From CI/CD pipeline


(b) Assertions and Validations

JUnit provides built-in assertion methods such as:

  • assertTrue()

  • assertEquals()

  • assertFalse()

  • assertNotNull()

Playwright also provides:

  • assertThat(locator).isVisible()

  • assertThat(locator).hasText()

This combination makes validation very powerful.


(c) Lifecycle Management

JUnit provides annotations such as:

  • @BeforeAll

  • @AfterAll

  • @BeforeEach

  • @AfterEach

These help manage:

  • Browser setup

  • Context initialization

  • Cleanup after execution


(d) Parallel Execution

Both Playwright and JUnit support parallel test execution, which:

  • Reduces test execution time

  • Improves efficiency

  • Helps large automation suites


(e) CI/CD Integration

JUnit generates XML/HTML reports that integrate easily with:

  • Jenkins

  • GitHub Actions

  • GitLab CI

  • Maven

  • Azure DevOps

This makes automated testing part of continuous integration.


Common Assertion Types in Playwright Java

Below are the most commonly used assertions in Playwright:

Assertion TypeMethod
Element is visibleassertThat(locator).isVisible();
Element has textassertThat(locator).hasText("value");
Element is enabledassertThat(locator).isEnabled();
Element is hiddenassertThat(locator).isHidden();
Element contains valueassertThat(locator).hasValue("value");
Title verificationpage.title() + JUnit assertion


Example: Login Page Assertion in Playwright Java

Let’s use the login page:

https://opensource-demo.orangehrmlive.com/web/index.php/auth/login

We will verify:

  • Page title

  • Username field visibility

  • Login button enabled

  • Placeholder text


Step 1: Add Maven Dependencies

Add the following dependencies in pom.xml:

<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.10.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.10.2</version> <scope>test</scope> </dependency>

Make sure you use the latest stable versions.


Step 2: Complete Playwright + JUnit Code

import com.microsoft.playwright.*; import org.junit.jupiter.api.*; import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat; public class LoginTest { static Playwright playwright; static Browser browser; static Page page; static BrowserContext context; @BeforeAll static void setup() { playwright = Playwright.create(); browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); context = browser.newContext(); page = context.newPage(); } @Test void testLoginPageAssertions() { page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login"); // Title Assertion String title = page.title(); Assertions.assertTrue(title.contains("OrangeHRM"), "Page title does not match"); // Username field visibility Locator usernameField = page.locator("input[name='username']"); assertThat(usernameField).isVisible(); // Login button enabled Locator loginButton = page.locator("button[type='submit']"); assertThat(loginButton).isEnabled(); // Placeholder verification Assertions.assertEquals("Username", usernameField.getAttribute("placeholder")); } @AfterAll static void tearDown() { context.close(); browser.close(); playwright.close(); } }


Detailed Code Explanation

Let’s understand each section clearly.


Playwright.create()

Initializes the Playwright engine.

Without this, browser automation cannot start.


browser.newContext()

Creates a fresh browser session.

Think of it as opening a new incognito window.

This ensures:

  • No cache

  • No cookies

  • Clean test environment


page.navigate()

Opens the specified URL.


Locator

Locator usernameField = page.locator("input[name='username']");

Locator identifies elements in the DOM.

Playwright uses smart waiting, meaning it automatically waits for elements to appear.


Playwright Assertion

assertThat(usernameField).isVisible();

Checks if the element is visible.

If not, the test fails immediately.


JUnit Assertion

Assertions.assertTrue(title.contains("OrangeHRM"));

Validates the page title using JUnit.


@BeforeAll and @AfterAll

These manage:

  • Setup before all tests

  • Cleanup after execution

This ensures no browser instances remain open.


Why Use Playwright Assertions Instead of Only JUnit?

Playwright assertions provide:

  • Auto-waiting

  • Retry mechanism

  • Better error messages

  • Synchronization handling

For example:

assertThat(locator).hasText("Dashboard");

This waits until text appears.

JUnit does not provide auto-waiting.


Best Practices for Writing Assertions

✔ Prefer Playwright assertions for UI elements
✔ Use JUnit assertions for non-UI values
✔ Avoid Thread.sleep()
✔ Use descriptive error messages
✔ Validate both positive and negative scenarios
✔ Always close browser in teardown


Real-World Assertion Examples

Verify Error Message

Locator errorMsg = page.locator(".error-message"); assertThat(errorMsg).hasText("Invalid credentials");


Verify URL

Assertions.assertTrue(page.url().contains("dashboard"));


Verify Element Count

assertThat(page.locator(".menu-item")).hasCount(5);


Common Mistakes in Assertions

❌ Not waiting for page load
❌ Using hard waits
❌ Verifying unstable text
❌ Using incorrect locators
❌ Ignoring dynamic behavior


Advanced Tip: Using Soft Assertions (JUnit Alternative)

If you want multiple validations in a single test without stopping execution, consider using soft assertion libraries like AssertJ.


Why Assertions Are Critical in Automation Testing

Without assertions:

  • Tests cannot validate outcomes

  • Automation loses meaning

  • Failures go unnoticed

  • CI/CD loses reliability

Assertions transform automation scripts into true test cases.


Interview Questions on Playwright Assertions

  1. What is the difference between Playwright assertion and JUnit assertion?

  2. Why is auto-wait important in UI testing?

  3. How do you verify element visibility?

  4. How do you validate dynamic text?

  5. How do you handle assertions in parallel tests?


Suggested Posts:

1. Trace Viewer in Playwright
2. File Download in Playwright
3. Comma Selectors in Playwright
4. Handle Dynamic Webtable in Playwright
5. Page Object Model in Playwright