Playwright Java Tutorial: Building a QA Automation Framework
Build a production-ready Playwright Java QA automation framework with Maven, TestNG, Page Object Model, and GitHub Actions CI/CD.
Most Java QA teams do not fail because they cannot click a login button. They fail when a handful of scripts becomes a 200-test suite that flakes in CI, breaks on every CSS rename, and takes 40 minutes to tell you anything useful.
That is the gap this Playwright Java tutorial is built to close. You will not stop at a hello-world script. You will build a production-ready java test automation framework with Maven, TestNG, Page Object Model, thread-safe browser lifecycle, GitHub Actions, and TestDino for results you can trust across runs.
By the end of this guide you will have:
-
A Maven project with Playwright Java 1.63.0 and TestNG
-
A BaseTest that is safe to run in parallel
-
Page objects that hide locators from tests
-
Auto-waiting assertions instead of Thread.sleep()
-
Traces, screenshots, and video on failure
-
A GitHub Actions pipeline that runs on every pull request
If your team is still on Selenium, keep the language and the toolchain. Swap the browser engine. That is the fastest path from a brittle WebDriver suite to stable browser automation.
Why use Playwright Java for a Java test automation framework?
Playwright Java is Microsoft's official Java SDK for Playwright, the open-source browser automation library. It drives Chromium, Firefox, and WebKit from Java code through a single API, with first-class Maven and Gradle support.
Playwright talks to the browser over a persistent WebSocket connection. Selenium Java still goes through the HTTP WebDriver protocol and a separate driver binary. That architectural difference is why Playwright Java tests wait automatically, start faster, and flake less once the framework is set up correctly.
Playwright Java is an official binding, not a community wrapper. New features land in Java on the same release cadence as the other language bindings.
What Playwright Java gives you out of the box:
-
One API for Chromium, Firefox, and WebKit
-
Auto-waiting before every click, fill, and navigation
-
Isolated BrowserContext sessions for parallel tests
-
Built-in tracing, screenshots, video, and network interception
-
APIRequestContext for API setup alongside UI flows
-
No ChromeDriver, GeckoDriver, or Selenium Grid required
Playwright Java officially supports Java 8 or higher. For a new framework in 2026, use Java 17 LTS. That matches what most enterprise CI images already run and keeps you on a supported JDK.
Java is still the default language for enterprise QA. Teams already have Maven, TestNG or JUnit, and JVM-based CI. Playwright Java fits that world instead of asking everyone to rewrite tests in TypeScript. The Java API is an official binding, so you are not depending on a community wrapper.

For a new Java suite, Playwright wins on wait strategy, debugging, and CI setup time. Keep Selenium only when you still need Internet Explorer, a large WebDriver investment, or a vendor grid you are not ready to leave.
A move from Selenium is a framework rebuild, not a find-and-replace. The language stays Java. The browser layer, waits, and page objects change.
Note: Cypress has no official Java binding. If your product code and existing tests are Java, Playwright Java is the modern option that does not split the team across two languages.
Playwright Java Maven setup
A working Playwright Java Maven project takes a few minutes. You need:
-
JDK 17 (Java 8 works, Java 17 is what you should standardize on)
-
Maven 3.8+
-
IntelliJ IDEA or VS Code with the Java Extension Pack
Playwright downloads its own browser binaries. You do not install ChromeDriver.
Step 1: Create a Maven project
mvn archetype:generate -DgroupId=com.yourcompany.tests \
-DartifactId=playwright-java-framework \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DarchetypeVersion=1.4 \
-DinteractiveMode=false
Step 2: Add Playwright Java and TestNG to pom.xml
Pin versions in properties so upgrades stay in one place. This pom.xml uses Playwright 1.63.0, the current stable Java binding as of September 2026.
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<playwright.version>1.63.0</playwright.version>
<testng.version>7.11.0</testng.version>
</properties>
<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>${playwright.version}</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
Step 3: Install browser binaries
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI \
-D exec.args="install --with-deps chromium"
Tip: Install only the browsers you run in CI. Chromium covers Chrome and Edge for most Java teams. Add Firefox or WebKit later with install --with-deps firefox or webkit.
Gradle alternative
Playwright Java works the same if your org standardizes on Gradle:
dependencies {
testImplementation 'com.microsoft.playwright:playwright:1.63.0'
testImplementation 'org.testng:testng:7.11.0'
}
The CLI install command and the Java API do not change. This tutorial stays on Maven because that is still the default for most Java QA orgs.
Playwright Java example: your first test
Before you design folders and page objects, prove the binding works. This Playwright Java example launches Chromium, opens a page, and asserts the title with Playwright's own assertions.
package com.yourcompany.tests;
import com.microsoft.playwright.*;
import org.testng.annotations.Test;
import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class SmokeTest {
@Test
public void playwrightDevTitleContainsPlaywright() {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(
new BrowserType.LaunchOptions().setHeadless(true)
);
Page page = browser.newPage();
page.navigate("https://playwright.dev/java/");
assertThat(page).hasTitle(Pattern.compile("Playwright"));
browser.close();
}
}
}
Run it:
mvn test -Dtest=SmokeTest
If the title assertion passes, Maven, JDK, Playwright Java, and Chromium are wired correctly. The rest of this guide turns that script into a framework you can scale.
PlaywrightAssertions.assertThat() is the Java equivalent of Playwright's web-first expect(). These assertions retry until the condition is true or the timeout expires, which is why they belong in UI tests instead of raw TestNG Assert.assertEquals on page text you just read once.
Building the project structure
A java test automation framework is a folder contract. Tests never own locators. Page objects never launch browsers. Config never lives as string literals inside @Test methods.
playwright-java-framework/
├── src/
│ └── test/java/com/yourcompany/
│ ├── base/
│ │ └── BaseTest.java
│ ├── pages/
│ │ ├── LoginPage.java
│ │ └── DashboardPage.java
│ ├── tests/
│ │ └── LoginTest.java
│ └── utils/
│ ├── ConfigReader.java
│ └── ScreenshotHelper.java
├── src/test/resources/
│ ├── testng.xml
│ └── config.properties
├── .github/workflows/
│ └── playwright-ci.yml
└── pom.xml

When a locator changes, you edit one page class. When CI needs a different base URL, you change config.properties or an environment variable.
config.properties
baseUrl=https://your-app.com
headless=true
defaultTimeout=30000
navigationTimeout=60000
browser=chromium
ConfigReader
Read environment variables first, then the properties file. That lets GitHub Actions override baseUrl without a code change.
package com.yourcompany.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public final class ConfigReader {
private static final Properties PROPS = new Properties();
static {
try (InputStream in = ConfigReader.class.getClassLoader()
.getResourceAsStream("config.properties")) {
if (in == null) {
throw new IllegalStateException("config.properties not found on classpath");
}
PROPS.load(in);
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}
private ConfigReader() {}
public static String get(String key) {
String envKey = key.replace('.', '_').toUpperCase();
String fromEnv = System.getenv(envKey);
if (fromEnv != null && !fromEnv.isBlank()) {
return fromEnv;
}
String value = PROPS.getProperty(key);
if (value == null) {
throw new IllegalArgumentException("Missing config key: " + key);
}
return value;
}
public static boolean getBoolean(String key) {
return Boolean.parseBoolean(get(key));
}
public static double getDouble(String key) {
return Double.parseDouble(get(key));
}
}
Note: Keep utils separate from pages and tests. Screenshot helpers, config readers, and test-data factories get reused. Mixing them into page classes is how frameworks turn into dump drawers.
A thread-safe BaseTest class
This is the file that decides whether Playwright Java TestNG parallel execution works or silently corrupts sessions.
Playwright objects are not thread-safe. Create one Playwright instance per thread, reuse Browser on that thread, and give every test a fresh BrowserContext. If you store Page on a shared instance field and set parallel="methods", tests steal each other's pages.
What a BrowserContext is
Definition: A BrowserContext in Playwright Java is an isolated browser profile: its own cookies, local storage, and session. Create one context per test so parallel runs never share login state.
Production BaseTest
Create Playwright and Browser once per worker thread. Create Context and Page per @Test. Save a trace only when the test fails.
package com.yourcompany.base;
import com.microsoft.playwright.*;
import com.yourcompany.utils.ConfigReader;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import java.nio.file.Paths;
public abstract class BaseTest {
private static final ThreadLocal<Playwright> TL_PLAYWRIGHT = new ThreadLocal<>();
private static final ThreadLocal<Browser> TL_BROWSER = new ThreadLocal<>();
private static final ThreadLocal<BrowserContext> TL_CONTEXT = new ThreadLocal<>();
private static final ThreadLocal<Page> TL_PAGE = new ThreadLocal<>();
protected Page page() {
return TL_PAGE.get();
}
protected BrowserContext context() {
return TL_CONTEXT.get();
}
@BeforeMethod(alwaysRun = true)
public void setUp() {
if (TL_PLAYWRIGHT.get() == null) {
Playwright playwright = Playwright.create();
TL_PLAYWRIGHT.set(playwright);
Browser browser = playwright.chromium().launch(
new BrowserType.LaunchOptions()
.setHeadless(ConfigReader.getBoolean("headless"))
);
TL_BROWSER.set(browser);
}
BrowserContext context = TL_BROWSER.get().newContext(
new Browser.NewContextOptions()
.setViewportSize(1280, 720)
.setRecordVideoDir(Paths.get("target/videos/"))
);
context.setDefaultTimeout(ConfigReader.getDouble("defaultTimeout"));
context.setDefaultNavigationTimeout(ConfigReader.getDouble("navigationTimeout"));
context.tracing().start(new Tracing.StartOptions()
.setScreenshots(true)
.setSnapshots(true)
.setSources(true)
);
TL_CONTEXT.set(context);
TL_PAGE.set(context.newPage());
}
@AfterMethod(alwaysRun = true)
public void tearDown(ITestResult result) {
BrowserContext context = TL_CONTEXT.get();
if (context != null) {
if (result.getStatus() == ITestResult.FAILURE) {
context.tracing().stop(new Tracing.StopOptions()
.setPath(Paths.get("target/traces/" + result.getName() + ".zip"))
);
} else {
context.tracing().stop();
}
context.close();
}
TL_CONTEXT.remove();
TL_PAGE.remove();
}
}
Why this shape works:
-
Playwright + Browser stay on a ThreadLocal, so parallel methods cannot share them
-
Context + Page are created per test, so cookies and storage never leak
-
Traces are written only on failure, which keeps CI artifacts small
-
Timeouts come from config, not hardcoded magic numbers
If you are still learning and running tests sequentially, the simpler official pattern is fine: @BeforeClass for Playwright/Browser, @BeforeMethod for Context/Page. Switch to ThreadLocal before you turn on parallel="methods".
CI jobs exit after the suite, so leftover browser processes are reaped with the JVM. For long-lived local runs, close each thread's Playwright instance in a TestNG ITestListener on suite finish rather than in @AfterClass (that hook only sees one thread).
Page Object Model in Playwright Java
The Page Object Model (POM) is how Playwright Java tests stay readable after the 50th spec. Each page gets a class. That class owns locators and user actions. Tests call methods like loginAs(), never fill() on a raw CSS selector.
Tip: Name methods after the user goal, not the widget. loginAs(username, password) is a page object. fillUsernameField() plus clickLoginButton() is just a scattered test wearing a class name.
LoginPage
Prefer getByRole and getByTestId. They survive CSS refactors better than #login > div:nth-child(2).
package com.yourcompany.pages;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.AriaRole;
public class LoginPage {
private final Page page;
private final Locator usernameField;
private final Locator passwordField;
private final Locator loginButton;
private final Locator errorMessage;
public LoginPage(Page page) {
this.page = page;
this.usernameField = page.getByTestId("username");
this.passwordField = page.getByTestId("password");
this.loginButton = page.getByRole(
AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Log in")
);
this.errorMessage = page.getByRole(AriaRole.ALERT);
}
public void navigateTo(String baseUrl) {
page.navigate(baseUrl + "/login");
}
public DashboardPage loginAs(String username, String password) {
usernameField.fill(username);
passwordField.fill(password);
loginButton.click();
return new DashboardPage(page);
}
public String getErrorMessage() {
errorMessage.waitFor();
return errorMessage.textContent();
}
}
DashboardPage
package com.yourcompany.pages;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.AriaRole;
public class DashboardPage {
private final Page page;
private final Locator welcomeBanner;
private final Locator logoutButton;
public DashboardPage(Page page) {
this.page = page;
this.welcomeBanner = page.getByTestId("welcome-msg");
this.logoutButton = page.getByRole(
AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Log out")
);
}
public String getWelcomeMessage() {
welcomeBanner.waitFor();
return welcomeBanner.textContent();
}
public LoginPage logout() {
logoutButton.click();
return new LoginPage(page);
}
}

Returning the next page from loginAs() is optional, but it makes flows chain cleanly: new LoginPage(page()).loginAs(user, pass).getWelcomeMessage().
Locators and assertions
Locator choice is the difference between a stable Playwright Java suite and a weekend of CSS firefighting. Prefer locators that describe what the user sees, and use retrying assertions for anything that lives on the page.
Use this order:
- getByRole:buttons, links, headings, alerts
- getByLabel / getByPlaceholder, form fields
- getByTestId, when the app team can add data-testid
- getByText, unique visible copy
- CSS / XPath last resort
page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Save"));
page.getByLabel("Email");
page.getByPlaceholder("Search");
page.getByTestId("user-menu");
page.getByText("Welcome back");
Auto-waiting is already on. click() and fill() wait until the element is attached, visible, stable, enabled, and receiving events. You almost never need Thread.sleep().
For assertions, prefer Playwright's retrying matchers over TestNG's one-shot asserts on a string you captured too early:
import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
assertThat(page()).hasURL(Pattern.compile(".*/dashboard"));
assertThat(page().getByTestId("welcome-msg")).containsText("Welcome");
assertThat(page().getByRole(AriaRole.ALERT)).isVisible();
Tip: TestNG Assert is fine for values you already hold in Java (config, API status codes, computed totals). For anything on the page, use assertThat() so Playwright can retry while the UI settles.
Writing and running Playwright Java TestNG tests
With BaseTest and page objects in place, a test has one job: arrange the scenario, call the page, assert the outcome.
package com.yourcompany.tests;
import com.yourcompany.base.BaseTest;
import com.yourcompany.pages.DashboardPage;
import com.yourcompany.pages.LoginPage;
import com.yourcompany.utils.ConfigReader;
import org.testng.annotations.Test;
import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class LoginTest extends BaseTest {
@Test(description = "Valid login navigates to dashboard")
public void validLoginShowsDashboard() {
LoginPage loginPage = new LoginPage(page());
loginPage.navigateTo(ConfigReader.get("baseUrl"));
DashboardPage dashboard = loginPage.loginAs(
"admin@example.com",
"SecurePass123"
);
assertThat(page()).hasURL(Pattern.compile(".*/dashboard"));
assertThat(page().getByTestId("welcome-msg")).containsText("Welcome");
org.testng.Assert.assertTrue(
dashboard.getWelcomeMessage().contains("Welcome"),
"Dashboard welcome message should be visible after login"
);
}
@Test(description = "Invalid credentials show an error")
public void invalidLoginShowsError() {
LoginPage loginPage = new LoginPage(page());
loginPage.navigateTo(ConfigReader.get("baseUrl"));
loginPage.loginAs("wrong@example.com", "wrongpassword");
assertThat(page().getByRole(
com.microsoft.playwright.options.AriaRole.ALERT
)).containsText("Invalid username or password");
}
}
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="PlaywrightSuite" verbose="1">
<test name="LoginTests">
<classes>
<class name="com.yourcompany.tests.LoginTest"/>
</classes>
</test>
</suite>
mvn test
Tracing a failure
When a test fails, BaseTest writes target/traces/<method>.zip. Open it at trace.playwright.dev with no local install. You get DOM snapshots, network, console, and the exact click that missed.
Start with the trace. It shows the DOM, network, and the exact action that missed, which is faster than rereading logs.
Parallel execution and GitHub Actions CI/CD
Parallel execution is where a Playwright Java framework pays for itself. Each TestNG method already has its own BrowserContext. Turn on parallel methods only after BaseTest is thread-safe.
TestNG parallel config
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="PlaywrightSuite" parallel="methods" thread-count="4" verbose="1">
<test name="LoginTests">
<classes>
<class name="com.yourcompany.tests.LoginTest"/>
</classes>
</test>
</suite>
Definition: parallel="methods" in TestNG runs each @Test on its own thread. Combined with Playwright Java's per-thread Playwright instance and per-test BrowserContext, you get isolation without Selenium Grid.
Start with thread-count equal to half your local cores. Raise it after the suite is stable. If tests share a backend user, they will still collide even with perfect browser isolation. Use unique test data or API setup via APIRequestContext.
GitHub Actions workflow
A Java CI job has three required moves: install OS dependencies, install browsers, then run mvn test. This workflow adds Maven caching and uploads failure artifacts.
name: Playwright Java Tests
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Java 17
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
cache: maven
- name: Install Playwright browsers
run: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps chromium"
- name: Run tests
run: mvn -B test
env:
BASEURL: ${{ secrets.TEST_BASE_URL }}
HEADLESS: "true"
- name: Upload Surefire reports
if: always()
uses: actions/upload-artifact@v4
with:
name: surefire-reports
path: target/surefire-reports/
retention-days: 7
- name: Upload traces and videos
if: always()
uses: actions/upload-artifact@v4
with:
name: playwright-artifacts
path: |
target/traces/
target/videos/
retention-days: 7
Tip: Cache Maven and install only Chromium. A cold Chromium download can add two to three minutes. Subsequent runs drop that to seconds. Once a single runner is too slow, split the suite across a few parallel CI jobs.

Playwright Java runs headless on ubuntu-latest without Xvfb. Set .setHeadless(true) and keep going.
Test reporting with TestDino
Surefire XML tells you whether this Maven run passed. It does not tell you which Playwright Java test failed 8 of the last 30 times.
Keep the evidence Playwright already writes:
-
target/traces/*.zip - open at trace.playwright.dev
-
target/videos/ - the browser session when a test fails
-
target/surefire-reports/ - the CI pass/fail check
That is one run. TestDino keeps the history. It groups failures by root cause and flags tests that are trending toward flakes before they block the pipeline. Watch these numbers:

-
Flakiness rate per test over the last 30 runs
-
Average duration and the slowest test by class
-
Time to first failure in CI
-
Failures by feature area, not just by class name
Review those trends in TestDino after every CI run. A single green Maven build hides a test that is already failing on other branches.
API setup beside UI tests
Use APIRequestContext to seed data instead of clicking through setup screens:
import com.microsoft.playwright.APIRequestContext;
import com.microsoft.playwright.APIResponse;
import com.microsoft.playwright.options.RequestOptions;
String email = "qa+" + System.nanoTime() + "@example.com";
APIRequestContext request = page().context().request();
APIResponse response = request.post(
ConfigReader.get("baseUrl") + "/api/users",
RequestOptions.create().setData("{\"email\":\"" + email + "\"}")
);
assertThat(response).isOK();
Create the user via API, then exercise the UI. Tests stay independent, which is the real prerequisite for parallel Playwright Java TestNG runs.
Playwright Java best practices
Use this as the framework checklist before you add the 100th test.
Framework design
-
One BaseTest, thread-safe before you enable parallel methods
-
Page objects for every screen you touch more than once
-
Config and secrets outside test classes
-
Unique test data per parallel worker
Locators and waits
-
getByRole / getByTestId first
-
No Thread.sleep() and no random waitForTimeout
-
Playwright assertThat() for UI state
-
Explicit locator.waitFor() only for known animations
Artifacts and CI
-
Traces, screenshots, and video on failure only
-
Chromium-only install on PR jobs
-
Maven cache in GitHub Actions
-
Review flake trends in TestDino instead of trusting one green build
Flakes you will actually see in Playwright Java
- Race on animated UI. Use locator.waitFor() for the state you need (visible, hidden, attached).
- Shared browser state. If two tests log into the same account, contexts will not save you. Isolate data.
- Shared Playwright objects across threads. This is the bug the ThreadLocal BaseTest exists to prevent.
- Slow CI navigation. Raise navigationTimeout in config, not inside one test with a sleep.
If a test fails and then passes on retry, fix the locator or the test data. A retry only filters noise in CI. It does not repair the test.
If you add Cucumber later, reuse these same page objects inside step definitions. Do not copy locators into the steps.
Conclusion
A Playwright Java automation framework is a system your team can extend at 200 tests without rewriting selectors in every class.
The production shape is small and strict:
-
Playwright Java 1.63+ on Java 17, Maven, and TestNG
-
Folder layers for base, pages, tests, and utils
-
Thread-safe browser lifecycle with one BrowserContext per test
-
Page Object Model so tests read like user journeys
-
Parallel methods only after isolation is real
-
Traces on failure, and TestDino for history across runs
-
GitHub Actions on every pull request
Playwright Java gives you the engine. The BaseTest and page objects decide whether that engine becomes a suite you trust. Start with the smoke test, then add structure before the third spec.
FAQs
playwright dependency (1.63.0 at the time of this article), then run mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps chromium". That is the full Playwright Java Maven setup. No ChromeDriver.APIRequestContext shares storage with the browser context when you use page.context().request(). Create test data over HTTP, then assert the UI. That pattern keeps UI tests short and parallel-safe.
Pratik Patel
Co-founder