Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To run Playwright automation tests in Java, add the Playwright Maven dependency, install the browser binaries for that exact version, then create a Playwright instance, launch a browser, open an isolated BrowserContext, and exercise the page with locators and retrying assertions. Playwright Java supports Chromium, Firefox, and WebKit in headed or headless mode, locally or in CI. The workflow below uses the dependency version shown in Microsoft’s current Java introduction (1.63.0); check the official documentation before pinning a version because releases and browser revisions change.

What you need before writing a test

  • Java 8 or later, subject to the operating-system support listed for your Playwright release.
  • Maven (or another build tool that can resolve Maven artifacts).
  • A test application that can be reached from the machine running the test.
  • Permission to download Playwright’s browser binaries and, on Linux, any required operating-system packages.

Playwright’s Java installation guide is the authority for currently supported Java and operating-system versions: Installation | Playwright Java.

Add Playwright to a Maven project

Add the dependency to pom.xml. The version below is the example displayed in the Java introduction retrieved for this article, not a promise that it will remain current.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.63.0</version>
</dependency>

Keep the Playwright library version and its browser installation in sync. After changing the dependency, rerun the browser installation command so the required revisions are present.

Install the browsers and system dependencies

From the project directory, use the Java CLI shipped with the dependency:

mvn exec:java 
  -e -D exec.mainClass=com.microsoft.playwright.CLI 
  -D exec.args="install"

On Linux CI, install operating-system dependencies as well:

mvn exec:java 
  -e -D exec.mainClass=com.microsoft.playwright.CLI 
  -D exec.args="install --with-deps"

If your pipeline only runs headless Chromium, the browser guide documents --only-shell as an option to install only the headless shell. Browser revisions are tied to Playwright releases, so repeat installation after an upgrade. Full command and platform guidance is in Browsers | Playwright Java.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Playwright can install branded Chrome or Edge, but those installations use the operating system’s default global location and can override an existing installation. Use that mode only when you understand the effect on the machine or CI image.

Your first Java test

This standalone class demonstrates the essential lifecycle. It opens a page in headless Chromium, checks a heading, and writes a screenshot. Replace the URL and expected text with values from your application.

import com.microsoft.playwright.*;

public class SmokeTest {
  public static void main(String[] args) {
    try (Playwright playwright = Playwright.create()) {
      Browser browser = playwright.chromium().launch(
          new BrowserType.LaunchOptions().setHeadless(true));
      try (BrowserContext context = browser.newContext()) {
        Page page = context.newPage();
        page.navigate("https://example.com");
        Locator heading = page.getByRole(
            AriaRole.HEADING,
            new Page.GetByRoleOptions().setName("Example Domain"));
        assert heading.isVisible();
        page.screenshot(new Page.ScreenshotOptions()
            .setPath(java.nio.file.Paths.get("page.png"))
            .setFullPage(true));
      }
      browser.close();
    }
  }
}

Use Playwright assertions rather than immediate, one-time reads when you need a condition to become true. Actions auto-wait for actionability (for example, an element becoming visible and enabled), and Playwright assertions retry until their timeout. Those behaviors are central to reducing timing-sensitive tests. See Writing tests | Playwright Java.

Use a test runner: JUnit or TestNG

The official runner guide documents both JUnit and TestNG. Choose the one that matches your project’s build plugins, reporting, lifecycle conventions, and parallel-execution strategy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

JUnit 5 pattern

import com.microsoft.playwright.*;
import org.junit.jupiter.api.*;

class LoginTest {
  static Playwright playwright;
  static Browser browser;
  BrowserContext context;
  Page page;

  @BeforeAll
  static void startBrowser() {
    playwright = Playwright.create();
    browser = playwright.chromium().launch();
  }

  @BeforeEach
  void newContext() {
    context = browser.newContext();
    page = context.newPage();
  }

  @Test
  void userCanOpenHomePage() {
    page.navigate("https://example.com");
    Assertions.assertTrue(page.getByRole(
        AriaRole.HEADING,
        new Page.GetByRoleOptions().setName("Example Domain")).isVisible());
  }

  @AfterEach
  void closeContext() { context.close(); }

  @AfterAll
  static void stopBrowser() {
    browser.close();
    playwright.close();
  }
}

Reusing one Playwright and Browser can reduce startup overhead, while creating a fresh BrowserContext (and Page) for every test keeps cookies, local storage, permissions, and other browser state isolated. If your suite runs tests in parallel, preserve that per-test context boundary and verify that your runner’s lifecycle hooks are thread-safe.

TestNG

TestNG uses the same Playwright objects and isolation model; map browser startup and shutdown to suite-level hooks and create/close a context around each test method. Follow the integration details and examples in Test Runners | Playwright Java rather than mixing JUnit annotations into a TestNG class.

Locators that survive UI changes

Prefer user-facing locators in this order when they express the contract clearly:

  • getByRole with an accessible name for buttons, links, headings, checkboxes, and form controls.
  • getByLabel for inputs associated with a visible label.
  • getByText for stable, user-visible text.
  • getByTestId when your application deliberately exposes a test-id contract.

Avoid long CSS or XPath chains tied to layout details. Scope a locator to a component when duplicate text exists:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Locator dialog = page.getByRole(AriaRole.DIALOG);
dialog.getByRole(AriaRole.BUTTON,
    new Locator.GetByRoleOptions().setName("Save")).click();

Use assertions that describe the expected state, such as visibility, text, URL, count, or an input value. Give genuinely slow operations an explicit timeout instead of inserting arbitrary sleeps. A fixed delay hides the real synchronization condition and makes tests slower when the page is already ready.

Generate a starting test with Codegen

Codegen records browser interactions and prioritizes role, text, and test-id locators. Start it with:

mvn exec:java 
  -e -D exec.mainClass=com.microsoft.playwright.CLI 
  -D exec.args="codegen https://your-app.example"

Use the generated Java as scaffolding, then replace incidental clicks with business-level assertions, remove unstable selectors, and add setup and cleanup appropriate to your test runner. The feature is described in Generating tests | Playwright Java.

Headed debugging versus headless CI

  • Headless: the usual CI choice; it avoids a visible window and works well in Linux containers when dependencies are installed.
  • Headed: launch with setHeadless(false) while diagnosing a selector, navigation, or authentication problem on a machine with a display.
  • Browser matrix: run the same critical flows against Chromium, Firefox, and WebKit when cross-engine behavior matters. Install all required binaries first.

Do not assume a test passing in Chromium proves equivalent behavior in every engine. Keep environment-specific failures attributable by recording the browser project, URL, and test data in your runner output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reliability practices for real suites

Make state explicit

Create a new context per test. Seed data through an API or fixture where possible, and avoid relying on the order in which tests happen to run.

Wait for conditions, not time

Use locator actions and retrying assertions. For a page that updates after a request, wait for the resulting UI state or a specific response rather than sleeping for an arbitrary number of milliseconds.

Control external variability

Use deterministic test accounts and data. If a third-party service is not part of the behavior under test, isolate it according to your application’s testing policy instead of letting an internet outage decide the result.

Keep artifacts useful

Save a screenshot or other diagnostic artifact only when it helps explain a failure, and name it with the test and browser. The introduction points readers toward traces as a next step; consult the current Java documentation for the exact trace-capture and inspection procedure before standardizing it.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common failures and fixes

Symptom Likely cause Fix
Executable missing or browser launch fails Browser binaries were not installed, or the Playwright version changed. Run the CLI install command again; on Linux use install --with-deps when required.
Linux launch reports missing shared libraries Container or host lacks browser OS dependencies. Install with --with-deps or bake the documented packages into the CI image.
Locator times out Wrong role/name, page not at the expected URL, or the element is genuinely unavailable. Inspect the rendered accessibility target, assert navigation first, and choose a stable role, label, text, or test-id locator.
Tests pass alone but fail in a suite Shared cookies, storage, or data between tests; unsafe parallel fixtures. Create and close a context per test and make test data independent.
Headed mode cannot start in CI No display server is available. Use headless mode, or configure the CI environment’s supported display solution only when visual debugging is necessary.
Branded Chrome/Edge behaves unexpectedly Global installation location or an existing installation was replaced. Review the browser guide’s branded-browser caveat and use the bundled browser unless a branded binary is a tested requirement.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, browser coverage, and cost decisions

Decision Practical effect
Reuse Playwright and Browser Less process startup overhead; contexts still isolate tests.
New Browser per test Strong isolation but slower and more resource-intensive.
Chromium only Fastest, simplest matrix when your product target is limited.
Chromium, Firefox, and WebKit Broader engine coverage with more runtime and maintenance.
Headless Suitable for most CI execution.
Headed Useful for interactive diagnosis; requires a display environment.

Playwright itself does not impose a per-test service fee; your costs are the machines, CI minutes, storage, and any environments your tests exercise. The right matrix depends on your supported browsers and release risk rather than an abstract “best” configuration.

Or skip the browser setup

If your immediate goal is a clean image or PDF of a URL rather than an interactive Java test, ScreenshotNeo provides a website screenshot API and MCP server. A single GET request can return PNG, JPEG, WebP, or PDF. Its browser workflow accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled.

Only clean shots are billed. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are marked in the response and cost nothing. The MCP server exposes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. Every plan includes features such as full-page lazy-image loading, CSS-selector element capture, device presets, custom JavaScript and CSS, request blocking, cookies and headers, geolocation, signed links, asynchronous webhooks, bulk capture, and a usage API.

cURL

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the complete parameter reference at ScreenshotNeo documentation. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Can Playwright Java test more than Chromium?

Yes. The Java browser documentation covers Chromium, Firefox, and WebKit, including their installation requirements. Select the engines that match your supported product surface.

Should every test launch its own browser?

Not usually. Reuse the Playwright and Browser objects when practical, but create a fresh BrowserContext and Page for each test to isolate state.

Is Codegen production-ready without edits?

No. It is a useful starting point; review its locators, remove incidental steps, and add assertions that express the behavior your test is intended to protect.

Frequently Asked Questions

Can Playwright Java test more than Chromium?

Yes. The Java browser documentation covers Chromium, Firefox, and WebKit, including their installation requirements. Select the engines that match your supported product surface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should every test launch its own browser?

Not usually. Reuse the Playwright and Browser objects when practical, but create a fresh BrowserContext and Page for each test to isolate state.

Is Codegen production-ready without edits?

No. It is a useful starting point; review its locators, remove incidental steps, and add assertions that express the behavior your test is intended to protect.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.