Recommended Free Tools
To use Playwright with Java TestNG, add the Playwright Java Maven dependency, install the browser binaries for that Playwright version, and manage the browser lifecycle with TestNG annotations. Reuse Playwright and Browser for the test class, but create a new BrowserContext and Page for each test method. That gives each test a clean browser session while avoiding the cost of launching a browser for every method.
What you need before you write a test
This guide assumes a Java Maven project that already runs TestNG tests. Playwright for Java is distributed as Maven modules. The official installation page shows com.microsoft.playwright:playwright at version 1.63.0; that is the version in the documentation example, not a guarantee that it is the latest release. Check the official Playwright Java installation guide and pin a version appropriate for your project.
Add the dependency to the existing <dependencies> section of pom.xml:
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.63.0</version>
</dependency>
Use the same version when installing browsers. A Playwright release expects particular browser binaries, so changing the Maven dependency can mean that the browser-install step must be run again. The Java setup documentation lists Java 8 or higher and supported operating systems, including Windows 11 or newer, Windows Server 2019 or newer, WSL, macOS 14 or newer, and specified Debian and Ubuntu releases for x86-64 or arm64. OS support changes over time; check the installation page for the requirements that apply to your version and machine.
Install Playwright’s browser binaries
After Maven resolves the dependency, install the browsers from the project directory. The Playwright Java CLI can install its default browser set, or just one engine:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install"
# Install one engine instead, for example:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install chromium"
For a CI agent that also needs operating-system libraries, the CLI offers a combined install command:
mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install --with-deps"
See the browser installation guide for current CLI details and the installation guide for Maven setup. A successful compile alone does not prove that the browser is installed: the Java library and the browser binary are separate parts of the setup.
Rank #2
Choose a lifecycle that isolates tests
The useful default is one Playwright runtime and one browser per TestNG class, with a fresh context and page for each test method. The Playwright TestNG guide recommends initializing Playwright and Browser in @BeforeClass and closing them in @AfterClass. A BrowserContext is an independent browser session: contexts do not share cookies or cache, and non-persistent contexts do not write browsing data to disk. Close each context before the shared browser so any artifacts can be flushed; see the BrowserContext and Browser API references.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →| Resource | Scope | Why |
|---|---|---|
Playwright |
Test class | Owns the Playwright API runtime. |
Browser |
Test class | Reuse the launched engine instead of starting it for every method. |
BrowserContext |
Test method | Separate cookies, cache, and session state between tests. |
Page |
Test method | Each test receives a fresh tab in its isolated context. |
Creating a browser for every test can simplify ownership, but costs extra startup time. Reusing a context and manually deleting cookies or storage can be faster in some suites, but makes tests dependent on cleanup correctness. Context-per-method is the safer default; change it only when you have a deliberate reason and reliable cleanup.
Create a TestNG test class
The following example uses Chromium and the public Example Domain page to demonstrate navigation, a role-based locator, and a web-first assertion. In an application suite, replace the URL and expected title with your own test environment. The example relies on the TestNG dependency already in your Maven project.
package example;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
public class ExampleDomainTest {
private Playwright playwright;
private Browser browser;
private BrowserContext context;
private Page page;
@BeforeClass
public void startBrowser() {
playwright = Playwright.create();
browser = playwright.chromium().launch(
new BrowserType.LaunchOptions().setHeadless(true));
}
@BeforeMethod
public void openIsolatedPage() {
context = browser.newContext();
page = context.newPage();
}
@Test
public void pageShowsExpectedContent() {
page.navigate("https://example.com");
assertThat(page).hasTitle("Example Domain");
assertThat(page.getByRole(
com.microsoft.playwright.options.AriaRole.HEADING,
new Page.GetByRoleOptions().setName("Example Domain")))
.isVisible();
}
@AfterMethod(alwaysRun = true)
public void closeTestContext() {
if (context != null) {
context.close();
context = null;
page = null;
}
}
@AfterClass(alwaysRun = true)
public void stopBrowser() {
if (browser != null) {
browser.close();
browser = null;
}
if (playwright != null) {
playwright.close();
playwright = null;
}
}
}
Run it with mvn test. TestNG recognizes the annotated method, while Playwright drives the browser. alwaysRun = true makes the cleanup hooks eligible to run even when a test fails; the null checks also make cleanup safe if setup failed partway through. If your suite can execute methods in parallel, do not let multiple methods overwrite the same instance fields: use a per-thread or per-test fixture design, or keep the class non-parallel. Shared Playwright objects should not become shared mutable test state by accident.
Use locators and assertions that survive normal page delays
Playwright locators are designed to wait and retry around page changes, which is preferable to guessing how long an element needs to appear. The writing tests guide shows locating content and checking visible outcomes. Prefer, in order where the page supports them:
- Accessible roles and names, such as a button named “Save”.
- Labels for form controls, where the UI exposes a label.
- Stable test IDs when the test needs a deliberate automation hook.
- Text or CSS selectors when they are stable and reflect the element you actually need.
For example, a form test can use page.getByLabel("Email"), fill a value, click page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Continue")), then assert that a confirmation message is visible. Use Playwright’s web-first assertions for browser-visible outcomes; use TestNG assertions for Java-side conditions or values already obtained. Avoid fixed sleeps as a routine synchronization strategy: they slow successful runs and still may be too short for a slow response.
Rank #4
Playwright’s Codegen can record interactions and suggest locators. Treat its output as a starting point: review the locator choices and assertions, remove incidental navigation or setup, and keep only steps that express the behavior the test is meant to protect.
Select Chromium, Firefox, or WebKit deliberately
Playwright supports Chromium, Firefox, and WebKit. Chromium is a reasonable default for a focused smoke suite; add the other engines when cross-browser behavior matters. Changing the engine is made through the corresponding Playwright browser type, for example playwright.firefox().launch() or playwright.webkit().launch(), and requires installing that engine’s browser binary. The browser guide describes browser management. Decide whether a test should run in all engines or only a targeted subset based on the behavior being checked and the time budget for the suite.
Run the suite in CI
A CI worker needs the Java project, Playwright’s matching browser binaries, and any operating-system dependencies required by those browsers before Maven runs the tests. A basic sequence is:
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Best Value
- Check out the repository and configure the required Java version for the project.
- Resolve the Maven project dependencies.
- Install the browser engine or engines used by the suite; use the dependency-install option where the worker needs system libraries.
- Run
mvn testand retain the test report as a CI artifact according to your team’s workflow.
The Playwright Java CI guide includes GitHub Actions and container examples. Use its current instructions as a base rather than pinning a workflow action or container version from an old snippet. If the Playwright dependency changes, review the CI browser-install step as part of the same update.
Common setup and test failures
- Browser executable missing: the Maven dependency is present but the binary is not. Run the Playwright CLI install command for the project’s Playwright version and selected engine.
- Browser fails to start on a CI machine: the agent may be missing OS libraries or may not support that browser setup. Follow the CI guide and use the CLI’s dependency installation option where appropriate.
- Tests pass alone but fail in a suite: cookies, cache, or page state may be leaking. Create and close a new context for each method instead of reusing a context.
- Element lookup times out: confirm the page reached the expected state, that the accessible role/name or selector still matches the UI, and that the element is not hidden or in a different frame. Prefer a locator and a meaningful assertion over a fixed delay.
- Title or text assertion fails intermittently: verify that navigation completed to the expected destination and that the assertion targets the final user-visible state, not a transient loading state.
- Tests interfere when run in parallel: avoid shared mutable page/context fields across concurrent test methods. Give each worker its own fixture resources or disable parallel execution for that class.
Or skip the browser setup
If the job is to save a page as an image or PDF rather than interact with it as a TestNG browser test, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns an image or PDF. For example, using cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
See the ScreenshotNeo API documentation for request options. It removes cookie/consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. ScreenshotNeo is for captures, not a replacement for Playwright’s interactive assertions or a TestNG end-to-end suite. Sign up free for 1,000 screenshots a month, with no card.
Frequently Asked Questions
Can I use Playwright’s Java setup in a Gradle project?
The installation example here is for Maven. The cited Java installation guide is the place to check for the current dependency and browser setup guidance for your build environment.
Can I keep a signed-in user session between test methods?
You can choose to persist or reuse state when a test specifically needs it, but that changes the isolation model. Keep such setup explicit so unrelated tests do not depend on it.
Does ScreenshotNeo run TestNG tests?
No. ScreenshotNeo returns page screenshots or PDFs; TestNG and Playwright remain the tools for executing and asserting interactive browser tests.
Quick Recap
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.




