Mastering Test Automation with Playwright Java

Learn how to use Playwright with Java for advanced test automation. Run tests on BrowserStack to execute cross-browser and real-device automation reliably.

guide-banner-qals-1x
Home Guide Mastering Test Automation with Playwright Java

Mastering Test Automation with Playwright Java

Playwright with Java is becoming a preferred choice for testers who want reliable, scalable, and fast end-to-end testing. It combines the modern automation capabilities of Playwright with the flexibility of Java, making it easier to build maintainable test suites.

Overview

What is Playwright Java?

Playwright Java is the Java language binding of the Playwright framework, which allows developers and testers to write automation scripts in Java while leveraging Playwright’s powerful cross-browser testing features.

Can Playwright be used with Java?

Yes, Playwright provides official support for Java, enabling teams already working in Java-based environments to seamlessly adopt Playwright without switching to another language.

Benefits of Test Automation with Playwright and Java

  • Cross-browser support: Automates tests across Chromium, Firefox, and WebKit.
  • Parallel execution: Runs multiple tests simultaneously for faster feedback.
  • Strong integration: Works smoothly with popular Java test frameworks like JUnit and TestNG.
  • Rich API: Provides reliable automation for UI interactions, network interception, and more.
  • CI/CD friendly: Easily integrates into Jenkins, GitHub Actions, or other pipelines.

This article explains how Playwright and Java work together to simplify modern test automation and improve software quality.

What is Playwright Java?

Playwright Java is the Java library (binding) for Playwright, a framework that automates web browsers. It allows Java programs to control browsers like Chrome, Firefox, Edge, and Safari to perform actions such as navigating pages, clicking elements, or extracting data. Essentially, it brings Playwright’s browser automation capabilities to the Java programming language.

Can Playwright be used with Java?

Yes, Playwright can be used with Java. Microsoft provides official Java bindings for Playwright, allowing Java developers to write scripts that automate browsers like Chrome, Firefox, Edge, and WebKit. This enables full browser automation directly from Java applications or test frameworks like JUnit and TestNG.

Benefits of Test Automation with Playwright and Java

Test automation with Playwright and Java enables precise and maintainable browser testing. It allows developers to automate complex user interactions across different browsers and environments so tests run consistently.

Below are key reasons why Playwright with Java is effective for automation:

  • Cross-Browser Support: Allows the same test scripts to run on Chrome, Firefox, Edge, and WebKit to uncover browser-specific issues without rewriting code.
  • Reliable Element Handling: Uses intelligent locators and automatic waiting to handle dynamic page content and asynchronous events so tests are less flaky and easier to maintain.
  • Parallel Test Execution: Runs multiple tests or browser instances at the same time to reduce total testing time and provide faster feedback in CI/CD pipelines.
  • Integration with Java Frameworks: Works with JUnit or TestNG to organize tests, perform assertions, and generate reports by leveraging familiar Java workflows.
  • Headless and Headed Modes: Supports headless execution to save resources or headed mode to debug and visually verify complex user interactions.
  • Consistent Automation API: Provides a single API to navigate pages, click elements, fill forms, and monitor network requests so complex workflows can be automated across all browsers.

Java and Playwright Integration

Setting up and configuring Java with Playwright is seamless, involving creating a Maven project, incorporating the Playwright dependency in the POM.xml file, and crafting Java code to initiate the browser and browse web pages.

This streamlined configuration and setup establish Java and Playwright as an unbeatable duo for effective web testing, enabling developers to dive into test automation swiftly and effortlessly.

Setting up Java and Playwright Integration 

Here, we are going to  set up a Playwright Java example and demonstrate using Eclipse IDE.

Maven Setup:

  1. Create a new Maven project by clicking on “New” -> “Project”.
  2. Choose “Maven Project” and proceed to the next step.
  3. Select the “Quickstart” archetype, provide a project name, and click “Finish”.

POM Configuration:

Add the following dependency to your project’s POM.xml file:

<dependencies>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.10.0</version>
</dependency>
</dependencies>

Save the XML file.

Playwright Java Example Code:

import com.microsoft.playwright.Playwright;

public class Play {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch();
Page page = browser.newPage();
page.navigate("http://www.browserstack.com/user/login");
System.out.println(page.title());
}
}
}
  • The code creates a Chromium browser instance and a new page within that instance.
  • You navigate to the specified website using the page.navigate() method.
  • Finally, we print the page title to confirm that Playwright is installed and functioning as expected.

Writing Test Cases in Java

  • Playwright has specialized assertions tailored for the dynamic web, automatically retrying checks until the conditions are met.
  • It also incorporates auto-wait functionality, waiting for elements to become actionable before executing actions.
  •  Additionally, Playwright provides “assertThat” overloads for conveniently writing assertions.

Here’s an example test showcasing the usage of web-first assertions, locators, and selectors

package org.example;

import java.util.regex.Pattern;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

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://www.browserstack.com/guide/writing-cypress-tests");


assertThat(page).hasTitle(Pattern.compile("Playwright"));

// create a locator
Locator getStarted = page.getByRole(AriaRole.LINK, new Page.GetByRoleOptions().setName("Get Started"));

When using Playwright, you can use “assertThat” overloads with a built-in waiting mechanism. This means the assertion will patiently wait until the expected condition is fulfilled before proceeding.

It ensures that you can rely on Playwright to handle your tests’ timing and synchronization aspects effortlessly.

import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

assertThat(page).hasTitle(Pattern.compile("Playwright"));

To enhance your testing capabilities, Playwright offers the flexibility to create custom locators using the Page.locator() method. Access to a wide range of locators, such as role, text, test ID, and more.

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

assertThat(page.locator("text=Installation")).isVisible();

Set up Playwright and Java

To set up Playwright with Java, you need to install Java and then proceed with setting up Playwright.

Here are the steps to install Java and set up Playwright in Java:

Installing Java

  1. You should start by visiting the official Java website. Choose the version of the Java Development Kit (JDK) that matches your OS.
  2. Once you’ve found the right version, it’s time to accept the license agreement and download the JDK installer file. Make sure to read and understand the terms before proceeding.
  3. With the JDK installer file, you can run it and follow the on-screen instructions. The installer will guide you through installing Java on your system. Just keep following the prompts, and you’ll be good to go.
  4. After the installation, it’s time to verify that Java is properly installed. Open a command prompt or terminal window and type java -version.
  5. If everything went smoothly, you should see information about the Java version displayed. This confirms that Java is successfully installed on your system.

Following these simple steps, you’ll have Java up and running, ready to be used with Playwright. Now you’re all set to dive into the exciting world of Playwright and unleash its power in your Java projects.

Setting up Playwright

If you want to leverage the power of Playwright in your project, here’s how you can easily set it up with Maven:

  1. You just need to add a single dependency to your project’s pom.xml file. This will make Playwright modules available for use in your project.
  2. If you’re new to Maven, don’t worry! You can refer to Maven’s documentation to better understand how it works. It’s a great tool for managing dependencies and building Java projects.

Creating your first Playwright-Java Test

Now that Playwright is set up with Java, you can start writing your first automated test. The goal here is to see Playwright in action by opening a browser, navigating to a web page, and performing basic checks.

Below is a simple step-by-step example to help you get started:

  • Initialize Playwright: Start by creating a Playwright instance in a try-with-resources block to ensure proper resource management.
  • Launch a Browser: Use the chromium().launch() method to start a Chromium browser instance. You can later switch to Firefox or WebKit if needed.
  • Open a New Page: Create a new page within the browser instance using browser.newPage(). This page is where all interactions will occur.
  • Navigate to a URL: Use the page.navigate(“URL”) method to go to the website you want to test.
  • Perform Assertions: Use Playwright’s assertThat() methods to verify page elements, titles, or visibility. Playwright automatically waits for conditions to be met, reducing the need for manual waits.
  • Interact with Elements: Create locators using page.getByRole(), page.locator(), or other locator strategies, and perform actions like click, fill, or hover.
  • Close Resources: The try-with-resources structure ensures the browser and Playwright instance close automatically after the test completes.

Here’s a minimal example combining these steps:

import com.microsoft.playwright.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;



public class FirstTest {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {

      Browser browser = playwright.chromium().launch();

      Page page = browser.newPage();

      page.navigate("https://example.com");

      assertThat(page).hasTitle("Example Domain");



      Locator moreInfo = page.locator("text=More information");

      moreInfo.click();

    }

  }

}

This basic test demonstrates opening a browser, navigating to a page, checking the title, and interacting with an element. Once comfortable with this workflow, you can extend it to more complex scenarios, multiple pages, and full end-to-end tests.

Integrating Playwright Java with JUnit and TestNG

After creating your first Playwright-Java test, the next step is to integrate it with popular Java testing frameworks like JUnit and TestNG. This integration allows you to organize tests, run them systematically, and generate detailed reports. It also enables seamless execution within CI/CD pipelines.

Below is how Playwright works with these frameworks:

1. JUnit Integration

JUnit provides a structured way to organize and run tests in Java. By integrating Playwright with JUnit, you can separate setup, test execution, and cleanup steps so tests are easier to read and maintain.

For example, @BeforeAll or @BeforeEach is used to start the browser or create pages before tests run. @AfterEach or @AfterAll is used to close pages and browsers after tests finish. Playwright’s assertThat() can then be used inside test methods to check page titles, elements, or visibility.

Here’s how to do it:

import com.microsoft.playwright.*;

import org.junit.jupiter.api.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;



public class JUnitPlaywrightTest {

  static Playwright playwright;

  static Browser browser;

  Page page;



  @BeforeAll

  static void setUp() {

    playwright = Playwright.create();

    browser = playwright.chromium().launch();

  }



  @BeforeEach

  void createPage() {

    page = browser.newPage();

  }



  @Test

  void testExampleTitle() {

    page.navigate("https://example.com");

    assertThat(page).hasTitle("Example Domain");

  }



  @AfterEach

  void closePage() {

    page.close();

  }



  @AfterAll

  static void tearDown() {

    browser.close();

    playwright.close();

  }

}

2. TestNG Integration

TestNG is similar to JUnit but offers more flexibility with configuration and grouping of tests. Integrating Playwright with TestNG allows you to initialize the browser once per class with @BeforeClass and clean it up with @AfterClass.

Individual pages can be opened and closed before and after each test method using @BeforeMethod and @AfterMethod. This ensures tests run independently while still reusing browser resources, keeping execution fast and consistent.

Here’s how to integrate it:

import com.microsoft.playwright.*;

import org.testng.annotations.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;



public class TestNGPlaywrightTest {

  Playwright playwright;

  Browser browser;

  Page page;



  @BeforeClass

  void setUp() {

    playwright = Playwright.create();

    browser = playwright.chromium().launch();

  }



  @BeforeMethod

  void createPage() {

    page = browser.newPage();

  }



  @Test

  void testExampleTitle() {

    page.navigate("https://example.com");

    assertThat(page).hasTitle("Example Domain");

  }



  @AfterMethod

  void closePage() {

    page.close();

  }



  @AfterClass

  void tearDown() {

    browser.close();

    playwright.close();

  }

}

Advanced Test Automation Techniques with Playwright and Java

Using Java’s object-oriented nature, you can write modular and reusable test scripts, while Playwright enables you to simulate complex user interactions effortlessly. Together, they enable you to build scalable and maintainable test automation frameworks.

The extensive ecosystem of Java libraries and frameworks further enriches your automation efforts.  Experience the seamless handling of pop-ups, effortless drag-and-drop actions, and efficient testing of multiple browser tabs.

Let’s understand more advanced techniques for Playwright and Java: a dynamic duo for advanced test automation.

1. Customizing Test Automation Framework

When it comes to customizing a test automation framework, Playwright is a compelling choice. Its extensive language support and powerful capabilities offer a seamless transition for those migrating from Selenium.

Playwright leverages the DevTools protocol, enabling robust and stable automated tests that provide deeper insights into the browser and more realistic user scenarios.

2. Managing Multiple Environments

Have you ever needed to test your application across different environments like development, staging, and production? With Playwright, you have the power to manage multiple test environments effortlessly.

  • You can easily configure Playwright to switch between different environments, ensuring that your tests are executed consistently against the right setup every time.
  • Replicate real-world scenarios in different environments, catching potential issues and ensuring a seamless user experience.
  • Playwright provides a flexible and intuitive way to handle environment-specific configurations such as URLs, credentials, and API endpoints.
  • With just a few lines of code, you can seamlessly run your tests across various environments, adapting them to different setups.
  • No more manual modifications of your test scripts whenever you want to switch environments.
  • By effectively managing multiple environments with Playwright, you can save valuable time and effort, focusing more on delivering high-quality software.

3. Parallel Test Execution

When it comes to parallel testing, Playwright plays a crucial role in executing multiple tests simultaneously across different browsers, saving you valuable time and effort. By harnessing the parallel testing capabilities of Playwright, you can run cross-browser tests effortlessly and ensure comprehensive test coverage.

BrowserStack Automate Banner

4. Handling Auto-Waiting and Mocking APIs for Advanced Automation

Playwright automatically waits for elements to become actionable, which reduces test flakiness when dealing with dynamic content. Combined with API mocking, you can simulate server responses, test edge cases, and isolate frontend behavior from backend dependencies. These capabilities help create highly reliable tests that handle asynchronous events and complex workflows.

Here’s an example that mocks an API response, waits for elements, and validates dynamic content:

import com.microsoft.playwright.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;



public class AdvancedTest {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {

      Browser browser = playwright.chromium().launch();

      BrowserContext context = browser.newContext();

      Page page = context.newPage();



      // Mock API response for a specific endpoint

      page.route("https://api.example.com/data", route -> {

        route.fulfill(new Route.FulfillOptions()

          .setStatus(200)

          .setContentType("application/json")

          .setBody("{\"items\":[\"A\",\"B\",\"C\"]}"));

      });



      // Navigate to page and auto-wait ensures elements are ready

      page.navigate("https://example.com/dashboard");



      // Auto-wait for element to be visible

      Locator table = page.locator("#data-table");

      assertThat(table).isVisible();



      // Perform actions only when elements are ready

      Locator refreshButton = page.locator("button#refresh");

      refreshButton.click();



      // Validate that mocked data appears in table

      assertThat(page.locator("text=A")).isVisible();

    }

  }

}

5. Parallelization, Test Isolation, and Running in Headless Mode

Advanced automation requires faster execution and reliable test separation. Playwright supports running multiple tests simultaneously in isolated browser contexts. Running tests in headless mode reduces resource usage while still maintaining full browser capabilities, making it ideal for CI/CD pipelines and large-scale test suites.

Here’s an example that runs tests in parallel with isolated contexts and headless browsers:

import com.microsoft.playwright.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;



public class ParallelTestExample {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {



      // Launch headless browser for parallel tests

      Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));



      // Create two independent contexts to isolate tests

      BrowserContext context1 = browser.newContext();

      BrowserContext context2 = browser.newContext();



      Page page1 = context1.newPage();

      Page page2 = context2.newPage();



      // Parallel test simulation

      page1.navigate("https://example.com/login");

      page2.navigate("https://example.com/dashboard");



      assertThat(page1.locator("input#username")).isVisible();

      assertThat(page2.locator("#dashboard-content")).isVisible();



      // Close contexts separately to ensure isolation

      context1.close();

      context2.close();



      browser.close();

    }

  }

}

Using Playwright for API Testing

While Playwright is primarily known for UI automation, it also offers powerful capabilities for API testing. You can send HTTP requests directly, validate responses, and even integrate these checks into end-to-end workflows. This makes it possible to test backend services, verify endpoints, and combine UI and API validations in a single framework.

Here’s an example that sends a GET request, validates the response, and extracts data:

import com.microsoft.playwright.*;



public class ApiTestExample {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {

      APIRequestContext apiRequest = playwright.request().newContext();



      // Send GET request to an API endpoint

      APIResponse response = apiRequest.get("https://api.example.com/users/1");



      // Validate response status

      if (response.status() == 200) {

        System.out.println("Status is 200 OK");

      }



      // Parse JSON response

      String body = response.text();

      System.out.println("Response Body: " + body);



      // Extract specific fields (example using JSON parsing)

      var json = response.json();

      System.out.println("User Name: " + json.get("name"));

    }

  }

}

Key Points:

  • Playwright’s APIRequestContext allows sending GET, POST, PUT, DELETE, and other HTTP requests.
  • You can validate status codes, headers, and response bodies directly within your tests.
  • API testing can be combined with UI tests to create full end-to-end workflows, such as validating that data submitted via UI appears correctly via API.
  • Mocking API responses is also possible to simulate backend behavior without relying on live services.

This approach lets you unify UI and API automation in Playwright, reducing context switching and enabling faster, more comprehensive testing.

Reporting and Debugging in Playwright Java

Automation is effective when failures can be understood, results can be tracked, and issues can be diagnosed quickly. Playwright Java provides built-in tools and integrations to make reporting and debugging straightforward for complex test suites.

Playwright can capture logs, take screenshots, and record videos of test runs. These artifacts show exactly what happened in the browser during a test. Integration with Java frameworks like JUnit or TestNG allows structured reporting of test results.

Here’s an example demonstrating screenshots, video recording, and console logging:

import com.microsoft.playwright.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;



public class ReportingDebuggingExample {

  public static void main(String[] args) {

    try (Playwright playwright = Playwright.create()) {

      Browser browser = playwright.chromium().launch();



      // Create a browser context with video recording

      BrowserContext context = browser.newContext(new Browser.NewContextOptions()

        .setRecordVideoDir("videos/"));



      Page page = context.newPage();



      // Navigate to a page

      page.navigate("https://example.com");



      // Take a screenshot

      page.screenshot(new Page.ScreenshotOptions().setPath("screenshots/example.png"));



      // Perform an assertion

      Locator heading = page.locator("h1");

      assertThat(heading).isVisible();



      // Capture console logs for debugging

      page.onConsoleMessage(msg -> System.out.println("Console: " + msg.text()));



      // Trigger an intentional failure to see video/screenshots in reports

      Locator nonExistent = page.locator("#does-not-exist");

      assertThat(nonExistent).isVisible();



      context.close();

      browser.close();

    }

  }

}

Key points for advanced reporting and debugging:

  • Screenshots: Capture the page state at any point to review failures visually.
  • Video Recording: Record full test sessions to analyze timing and user interactions.
  • Console Logs: Track JavaScript messages in real time to identify errors or warnings.
  • Framework Reporting: Use JUnit or TestNG reports to organize results alongside Playwright artifacts.
  • Trace Recording: Record full traces including screenshots, network requests, and DOM snapshots. Traces can be replayed in Playwright Trace Viewer for detailed debugging.

For teams running tests at scale, BrowserStack Automate can enhance Playwright debugging by providing access to 3,500+ real devices and browsers in the cloud, combined with built-in video recording, screenshots, and logs. This ensures that tests run reliably across different environments and helps identify platform-specific issues quickly, without maintaining local infrastructure.

Talk to an Expert

Best Practices for Playwright Java Test Automation

To create reliable, maintainable, and efficient test automation with Playwright and Java, it is important to follow practices that reduce flakiness, improve readability, and ensure consistent results.

Here are key best practices:

  • Use Auto-Waiting Effectively: Rely on Playwright’s built-in waiting mechanisms instead of hard-coded sleeps. This ensures actions are performed only when elements are ready and reduces test failures.
  • Isolate Tests with Browser Contexts: Create a new browser context for each test to avoid shared state such as cookies, local storage, or session data. This improves reliability and allows safe parallel execution.
  • Leverage Locators Over Selectors: Use Playwright locators like getByRole, getByText, or locator() instead of static CSS or XPath selectors. Locators are more stable and handle dynamic content automatically.
  • Organize Tests Using Frameworks: Integrate Playwright with JUnit or TestNG to structure tests, manage setup and teardown, and generate readable reports. This helps in maintaining large test suites.
  • Use Headless Mode for CI/CD: Run tests in headless mode during continuous integration to save resources while maintaining full browser capabilities.
  • Capture Artifacts for Debugging: Take screenshots, record videos, and use trace recording to analyze failures and track test behavior. This is essential for diagnosing complex or timing-sensitive issues.

Conclusion

Playwright Java offers a powerful and flexible solution for test automation. Its features such as auto-waiting, API mocking, parallel execution, and detailed reporting make it possible to create reliable and maintainable test suites.

Testing on BrowserStack takes Playwright automation further by enabling simultaneous execution across multiple devices, browsers, and operating systems. Teams can achieve broader test coverage, identify platform-specific issues quickly, and accelerate release cycles. Its centralized dashboard helps track results, analyze failures, and collaborate across development and QA teams.

Try BrowserStack for Free

Tags
Automation Testing Playwright

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord