1. Introduction
Browser automation is an important part of modern QA engineering. Automation testers use tools such as Selenium and Playwright to validate web applications, reduce manual effort, and improve regression testing.
Playwright Java is a browser automation library that allows Java developers and testers to automate web applications. It supports Chromium, Firefox, and WebKit through a single API.
If you already know Java and Selenium WebDriver, learning Playwright Java can help you expand your automation skills. Its built-in waiting mechanisms, modern locators, browser contexts, and debugging capabilities make it useful for developing reliable web testing solutions.
In this Playwright Java tutorial, you will learn how to install the library, launch a browser, interact with web elements, write JUnit tests, and create a reusable login automation example.
2. What Is Playwright Java?
Playwright Java is the official Java library provided by Microsoft for browser automation. It allows testers to perform actions such as:
- Opening websites and navigating between pages.
- Clicking buttons and entering text.
- Handling dropdowns, checkboxes, and forms.
- Validating page content and application behavior.
- Capturing screenshots.
- Testing applications across multiple browsers.
How does Playwright Java work?
Playwright uses a client-server architecture. Your Java code communicates with the Playwright driver, which controls the browser and performs the requested operations.
The basic workflow is:
- Create a Playwright instance.
- Launch a browser such as Chromium.
- Create a browser context.
- Open a page.
- Interact with the application.
- Validate the expected result.
- Close the browser resources.
Playwright Java vs Playwright Test
One important distinction for Java testers is that Playwright Test is not the Java test runner.
| Feature | Playwright Java | Playwright Test |
| Language | Java | JavaScript / TypeScript |
| Browser automation | Yes | Yes |
| Test runner | External runner such as JUnit or TestNG | Built-in Playwright Test runner |
| Build tool | Maven or Gradle | npm |
| Assertions | Playwright assertions and Java assertions | Playwright Test expect |
| Reporting | JUnit/TestNG and reporting tools | Built-in HTML and other reporters |
For Java projects, you normally combine the Playwright Java library with JUnit or TestNG.
3. Prerequisites
Before starting Playwright Java, install the following tools:
| Requirement | Purpose |
| Java JDK 8 or later | Run Java programs |
| Maven | Manage dependencies and execute tests |
| IntelliJ IDEA or Eclipse | Write and manage Java code |
| Internet connection | Download Maven dependencies and browser binaries |
| Supported operating system | Run supported Playwright browsers |
For a new project, Java 17 or a newer supported JDK is a practical choice.
Check your Java and Maven installations:
java -version
mvn -version
If both commands display version information, you are ready to create your project.
4. Playwright Java Installation
Follow these steps to configure Playwright Java using Maven.
Step 1: Create a Maven project
Open IntelliJ IDEA and create a new Maven project.
Use a project structure similar to this:
PlaywrightJavaProject
│
├── pom.xml
└── src
├── main
│ └── java
│ └── org.example
│ └── App.java
└── test
└── java
└── tests
└── LoginTest.java
Step 2: Add the Playwright dependency
Open pom.xml and add the official Playwright Java dependency.
<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.64.0</version>
</dependency>
</dependencies>
The version above is an example based on the current official documentation. Check the Playwright Java installation guide when creating a new project.
Step 3: Add JUnit 5
JUnit helps you organize and execute automated tests.
Add these dependencies inside the same dependencies section:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.4</version>
<scope>test</scope>
</dependency>
Configure Maven Surefire to execute JUnit 5 tests:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
</plugins>
</build>
Step 4: Install browser binaries
Playwright needs browser binaries to execute automation.
Run:
mvn compile
mvn exec:java -D exec.mainClass=”com.microsoft.playwright.CLI” -D exec.args=”install”
This installs the browsers supported by your Playwright installation. You can install a specific browser using the corresponding CLI option, such as install chromium.
5. First Playwright Java Program
Let’s write a simple Java program to launch Chromium, open a website, and retrieve its title.
Create App.java:
package org.example;
import com.microsoft.playwright.*;
public class App {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate(“https://playwright.dev”);
System.out.println(“Page Title: ” + page.title());
browser.close();
}
}
}
Run the program from your IDE or configure Maven’s Exec plugin and execute it with the appropriate main class.
Expected result:
Page Title: Fast and reliable end-to-end testing
The browser runs in headless mode by default. To see the browser window, use:
Browser browser = playwright.chromium().launch(
new BrowserType.LaunchOptions().setHeadless(false)
);
This is your first Playwright Java example.
6. Locators and Actions
Locators identify elements on a web page. Playwright provides several locator methods that help testers interact with application elements.
Common locator types
| Locator | Java example |
| CSS selector | page.locator(“#username”) |
| Text | page.getByText(“Welcome”) |
| Role | page.getByRole(AriaRole.BUTTON) |
| Label | page.getByLabel(“Email”) |
| Placeholder | page.getByPlaceholder(“Enter email”) |
| Test ID | page.getByTestId(“login-button”) |
Prefer user-facing locators such as role, label, and placeholder when they are available. CSS selectors are useful when the application provides stable attributes.
Click action
page.locator(“#login-button”).click();
Fill action
page.locator(“#username”).fill(“testuser”);
Keyboard action
page.locator(“#password”).fill(“password123”);
page.locator(“#password”).press(“Enter”);
You can also use role-based locators:
page.getByRole(
AriaRole.BUTTON,
new Page.GetByRoleOptions().setName(“Login”)
).click();
Playwright automatically performs actionability checks before many actions. This reduces the need for manual waits.
7. Assertions and Test Execution
Assertions verify whether an application behaves as expected.
Playwright Java provides its own assertion library. You can use it with JUnit 5 to create readable automated tests.
For example:
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
assertThat(page).hasTitle(“My Application”);
assertThat(page.locator(“#dashboard”)).isVisible();
These assertions wait and retry until the expected condition is satisfied or the assertion times out.
Execute tests using Maven
JUnit tests can be executed with:
mvn test
Maven Surefire discovers and runs the configured JUnit tests. Test results are generally available in:
target/surefire-reports/
8. Real-World Login Test Using Playwright Java
Now let’s create a practical login test using the public SauceDemo practice website.
The example uses:
- Website: https://www.saucedemo.com/
- Username: standard_user
- Password: secret_sauce
These are public practice-site credentials, not credentials to use on a real production account.
Step 1: Create a reusable LoginPage class
Create LoginPage.java:
package pages;
import com.microsoft.playwright.*;
public class LoginPage {
private final Page page;
private final Locator username;
private final Locator password;
private final Locator loginButton;
public LoginPage(Page page) {
this.page = page;
username = page.locator(“#user-name”);
password = page.locator(“#password”);
loginButton = page.locator(“#login-button”);
}
public void open() {
page.navigate(“https://www.saucedemo.com/”);
}
public void login(String user, String pass) {
username.fill(user);
password.fill(pass);
loginButton.click();
}
}
This class follows the Page Object Model (POM). It keeps page locators and actions separate from test logic, making the automation easier to maintain.
Step 2: Create a JUnit test
Create LoginTest.java:
package tests;
import com.microsoft.playwright.*;
import org.junit.jupiter.api.*;
import pages.LoginPage;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class LoginTest {
static Playwright playwright;
static Browser browser;
BrowserContext context;
Page page;
@BeforeAll
static void setupBrowser() {
playwright = Playwright.create();
browser = playwright.chromium().launch();
}
@BeforeEach
void setupTest() {
context = browser.newContext();
page = context.newPage();
}
@Test
void validLoginTest() {
LoginPage loginPage = new LoginPage(page);
loginPage.open();
loginPage.login(“standard_user”, “secret_sauce”);
assertThat(page.locator(“#inventory_container”))
.isVisible();
assertThat(page)
.hasURL(“https://www.saucedemo.com/inventory.html”);
}
@AfterEach
void closeContext() {
context.close();
}
@AfterAll
static void closeBrowser() {
browser.close();
playwright.close();
}
}
Step 3: Execute the login test
Run:
mvn test
Expected result:
- Browser launches.
- SauceDemo login page opens.
- Username and password are entered.
- Login button is clicked.
- Inventory page becomes visible.
- JUnit reports the test as passed if the assertions succeed.
This example demonstrates how Playwright Java can be used for real-world login validation and regression testing.
9. Screenshots and Reporting
Screenshots help testers investigate failures and share evidence with developers.
Add this code when you want to capture a screenshot:
import java.nio.file.Paths;
page.screenshot(
new Page.ScreenshotOptions()
.setPath(Paths.get(“target/login-success.png”))
);
Make sure the target directory exists before saving the screenshot.
Debugging options
For local debugging, launch the browser in headed mode:
Browser browser = playwright.chromium().launch(
new BrowserType.LaunchOptions()
.setHeadless(false)
.setSlowMo(500)
);
You can also use Playwright’s Inspector and debugging tools. Refer to the official Playwright debugging guide.
Test reports
JUnit and Maven Surefire produce test result files. For more detailed reports, you can integrate tools such as Allure with your JUnit project.
A typical reporting workflow includes:
- Execute automated tests.
- Collect passed and failed test results.
- Capture screenshots for important failures.
- Generate an HTML report using the selected reporting tool.
- Share the report with the QA team.
10. Best Practices and Common Mistakes
Follow these practices when developing a Playwright Java framework.
| Best practice | Why it matters |
| Prefer role and label locators | Improves locator reliability |
| Avoid fixed Thread.sleep() calls | Reduces unnecessary waiting |
| Use separate browser contexts | Prevents test data and session interference |
| Close browser resources | Avoids resource leaks |
| Use Page Object Model | Improves code reusability |
| Keep test data separate | Makes tests easier to maintain |
| Use meaningful assertions | Makes failures easier to understand |
Common mistakes
1. Using fixed waits
Avoid:
Thread.sleep(5000);
Prefer a condition-based assertion:
assertThat(page.locator(“#dashboard”)).isVisible();
2. Reusing the same browser context for every test
A browser context contains its own cookies and session storage. Create a fresh context for independent tests.
3. Using unstable XPath expressions
Long XPath expressions often break when the page structure changes. Prefer accessible locators or stable test IDs.
4. Forgetting cleanup
Close the context after each test and close the browser and Playwright instance after the test suite finishes.
11. CI/CD Integration
Playwright Java tests can run automatically through Jenkins or GitHub Actions. This helps teams execute browser tests whenever code changes are submitted.
A basic GitHub Actions workflow could look like this:
name: Playwright Java Tests
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
– name: Checkout code
uses: actions/checkout@v4
– name: Set up Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: ’17’
cache: maven
– name: Install dependencies
run: mvn -B compile
– name: Install Playwright browsers
run: >
mvn exec:java
-D exec.mainClass=”com.microsoft.playwright.CLI”
-D exec.args=”install –with-deps chromium”
– name: Run tests
run: mvn test
The workflow installs Java, downloads project dependencies, installs Chromium and its required system dependencies, and executes the JUnit tests.
For Jenkins, you can create a pipeline with similar stages: checkout, configure Java, install browser dependencies, run Maven tests, and publish test reports.
12. Playwright Java Interview Questions and FAQs
Q1. What is Playwright Java?
Playwright Java is a browser automation library that allows Java developers and QA engineers to automate web applications using Chromium, Firefox, and WebKit.
Q2. How do I get started with Playwright Java?
Install a supported Java JDK and Maven, create a Maven project, add the Playwright dependency, install browser binaries, and write your first Java automation program.
Q3. Is Playwright Java suitable for beginners?
Yes. Beginners with basic Java knowledge can learn Playwright Java step by step. Start with browser launch, navigation, locators, actions, and assertions before moving to framework development.
Q4. Does Playwright Java support Selenium-style automation?
Yes. Both tools automate browsers, but Playwright offers features such as browser contexts, built-in actionability checks, and modern locator APIs.
Q5. Which browsers are supported by Playwright Java?
Playwright Java supports Chromium, Firefox, and WebKit.
Q6. Can we use TestNG with Playwright Java?
Yes. Playwright Java can be integrated with TestNG. JUnit and TestNG are external test runners; Playwright Java itself does not provide the Playwright Test runner.
Q7. What is the Page Object Model?
Page Object Model is a design pattern in which each application page is represented by a Java class. The class stores locators and reusable page actions.
Q8. How do you handle waits in Playwright Java?
Playwright automatically waits for many actions and its assertions retry until the expected condition is met or the timeout expires. Prefer these mechanisms over fixed delays.
