Playwright Framework with Java: Complete Tutorial with Real-Time Automation Example

1. Introduction

Modern web applications require reliable and scalable test automation. As applications become more complex, QA teams need automation tools that support multiple browsers, faster execution, and maintainable test scripts.

Playwright is a browser automation library developed by Microsoft. It supports Chromium, Firefox, and WebKit and provides features for end-to-end testing, browser automation, API testing, and debugging.

Playwright supports several programming languages, including Java. This makes it useful for Java automation testers and Selenium professionals who want to learn a modern browser automation tool without changing their primary programming language.

A Playwright framework with Java combines the Playwright Java library with a test runner such as JUnit 5 or TestNG. It can also use Maven for dependency management, Page Object Model for reusable code, and reporting tools for test execution results.

Consider an e-commerce application. A Java automation framework might contain tests for:

  • User login and registration.
  • Product search and filtering.
  • Adding products to a shopping cart.
  • Checkout and payment workflows.
  • Order confirmation.

Instead of creating independent scripts for every workflow, we can build reusable components and organize the tests into a structured framework.

This tutorial explains how to create a practical Playwright Java framework from scratch.

2. What Is Playwright Framework with Java?

A Playwright framework with Java is a structured test automation solution that uses the official Playwright Java library to automate browser interactions.

It combines browser automation, Java programming, a test runner, reusable page objects, and reporting.

An important distinction is that Playwright Test is the built-in test runner for JavaScript and TypeScript. It is not the test runner for Java.

For Java projects, you can integrate Playwright with JUnit or TestNG.

Main framework components

ComponentResponsibility
Playwright JavaAutomates browser interactions
JavaImplements automation logic
MavenManages dependencies and builds
JUnit 5 or TestNGExecutes test cases
Page Object ModelOrganizes page locators and actions
Test dataStores test inputs
ConfigurationManages URLs and browser settings
ReportingDisplays execution results

Framework execution flow

JUnit / TestNG

      |

      v

Test Class

      |

      v

Base Test and Configuration

      |

      v

Page Object Model

      |

      v

Playwright Java Library

      |

      v

Browser

      |

      v

Web Application

      |

      v

Assertions and Reports

For example, a login test calls a method from the LoginPage class. That method interacts with the browser using Playwright locators. The test then verifies whether the dashboard appears.

3. Benefits of Using Java with Playwright

Java provides several advantages when developing a Playwright Test Automation Framework.

Java ecosystem support

Java has a mature ecosystem of testing libraries, build tools, reporting solutions, and CI/CD integrations. Teams already using Java can introduce Playwright without moving their entire automation codebase to JavaScript or TypeScript.

Object-oriented programming

Java supports classes, objects, inheritance, interfaces, and encapsulation. These features help developers create reusable automation components.

Maintainability

Page Object Model separates page interactions from test cases. If an application locator changes, the corresponding page object can be updated without modifying every test.

Integration with existing tools

Playwright Java can be integrated with:

Browser support

Playwright supports Chromium, Firefox, and WebKit. This allows teams to execute browser automation across different rendering engines.

4. Prerequisites and Project Setup

Before creating the framework, install:

  • Java Development Kit (JDK 17 recommended for this tutorial).
  • Maven.
  • IntelliJ IDEA or Eclipse.
  • Basic Java programming knowledge.
  • Basic understanding of HTML and web locators.

The official Playwright Java library supports Java 8 and higher, but using a currently supported JDK simplifies project maintenance.

Step 1: Create a Maven project

Create a Maven project named:

playwright-java-framework

You can create it using IntelliJ IDEA or from the command line.

Step 2: Add Maven dependencies

Open pom.xml and add the following dependencies and plugins.

The example uses Playwright Java 1.64.0 and JUnit Jupiter 5.12.2. Check the official documentation for the latest compatible releases when creating a new project.

<project xmlns=”http://maven.apache.org/POM/4.0.0″

         xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

         xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0

https://maven.apache.org/xsd/maven-4.0.0.xsd”>

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.techsarvam</groupId>

    <artifactId>playwright-java-framework</artifactId>

    <version>1.0-SNAPSHOT</version>

    <properties>

        <maven.compiler.release>17</maven.compiler.release>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <playwright.version>1.64.0</playwright.version>

        <junit.version>5.12.2</junit.version>

    </properties>

    <dependencies>

        <dependency>

            <groupId>com.microsoft.playwright</groupId>

            <artifactId>playwright</artifactId>

            <version>${playwright.version}</version>

        </dependency>

        <dependency>

            <groupId>org.junit.jupiter</groupId>

            <artifactId>junit-jupiter</artifactId>

            <version>${junit.version}</version>

            <scope>test</scope>

        </dependency>

    </dependencies>

    <build>

        <plugins>

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-surefire-plugin</artifactId>

                <version>3.5.3</version>

            </plugin>

            <plugin>

                <groupId>org.codehaus.mojo</groupId>

                <artifactId>exec-maven-plugin</artifactId>

                <version>3.5.0</version>

            </plugin>

        </plugins>

    </build>

</project>

Maven downloads the dependencies and makes them available to the project.

Step 3: Install browser binaries

Run the following command from the project directory:

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

This installs the browser binaries required by Playwright.

On supported Linux CI environments, you can install browser system dependencies as well:

mvn exec:java -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=”install –with-deps chromium”

5. Project Folder Structure

A maintainable framework separates test cases, page objects, configuration, and test data.

Recommended structure:

playwright-java-framework/

|

├── src/

│   ├── main/

│   │   └── java/

│   │       └── com/techsarvam/

│   │           ├── pages/

│   │           │   └── LoginPage.java

│   │           ├── config/

│   │           │   └── Config.java

│   │           └── testdata/

│   │               └── TestData.java

│   |

│   └── test/

│       └── java/

│           └── com/techsarvam/

│               ├── base/

│               │   └── BaseTest.java

│               └── tests/

│                   └── LoginTest.java

|

├── screenshots/

├── traces/

└── pom.xml

FolderPurpose
pagesContains reusable page object classes
configStores environment and browser settings
testdataStores test input data
baseContains common test setup and cleanup
testsContains JUnit or TestNG test classes
screenshotsStores failure screenshots
tracesStores Playwright trace files

This structure can be extended with API clients, utilities, authentication helpers, and reporting integrations as the project grows.

6. Writing Your First Playwright Java Test

Before building the complete framework, create a simple Java program to understand browser automation.

package com.techsarvam;

import com.microsoft.playwright.*;

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://playwright.dev/”);

            System.out.println(page.title());

            browser.close();

        }

    }

}

Explanation:

  • Playwright.create() initializes Playwright.
  • chromium().launch() launches Chromium.
  • browser.newPage() creates a page.
  • page.navigate() opens the website.
  • page.title() retrieves the page title.
  • The try-with-resources block closes the Playwright instance.

This is a basic browser automation script. For a professional framework, use JUnit or TestNG to manage test execution and assertions.

7. Building a Reusable Framework with Page Object Model

Page Object Model is a design pattern that separates web page interactions from test logic.

Let’s build a reusable login page.

Step 1: Create LoginPage.java

package com.techsarvam.pages;

import com.microsoft.playwright.Page;

public class LoginPage {

    private final Page page;

    public LoginPage(Page page) {

        this.page = page;

    }

    public void open(String baseUrl) {

        page.navigate(baseUrl + “/login”);

    }

    public void enterUsername(String username) {

        page.getByLabel(“Username”).fill(username);

    }

    public void enterPassword(String password) {

        page.getByLabel(“Password”).fill(password);

    }

    public void clickLogin() {

        page.getByRole(

            com.microsoft.playwright.options.AriaRole.BUTTON,

            new Page.GetByRoleOptions().setName(“Login”)

        ).click();

    }

}

The class stores the page object and provides reusable methods for login actions.

The accessible labels and button name must match the actual application.

Step 2: Create configuration

Create config/Config.java.

package com.techsarvam.config;

public class Config {

    public static String baseUrl() {

        return System.getProperty(

            “baseUrl”,

            “https://your-application-url.com”

        );

    }

    public static String browser() {

        return System.getProperty(

            “browser”,

            “chromium”

        );

    }

}

This configuration allows the URL and browser to be changed without editing the test class.

Step 3: Create test data

Create testdata/TestData.java.

package com.techsarvam.testdata;

public class TestData {

    public static final String USERNAME = “admin”;

    public static final String PASSWORD = “admin123”;

    public static final String INVALID_USERNAME = “wronguser”;

    public static final String INVALID_PASSWORD = “wrongpass”;

}

For real applications, do not commit production credentials or sensitive passwords to Git. Use environment variables or a secure CI secret store.

8. Real-World Login Test Example

Now connect the page object, configuration, and test data using JUnit 5.

Step 1: Create BaseTest.java

package com.techsarvam.base;

import com.microsoft.playwright.*;

import com.techsarvam.config.Config;

import org.junit.jupiter.api.*;

public class BaseTest {

    protected Playwright playwright;

    protected Browser browser;

    protected BrowserContext context;

    protected Page page;

    @BeforeEach

    void setUp() {

        playwright = Playwright.create();

        String browserName = Config.browser();

        switch (browserName.toLowerCase()) {

            case “firefox”:

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

                break;

            case “webkit”:

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

                break;

            default:

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

        }

        context = browser.newContext();

        page = context.newPage();

        context.tracing().start(

            new Tracing.StartOptions()

                .setScreenshots(true)

                .setSnapshots(true)

                .setSources(true)

        );

    }

    @AfterEach

    void tearDown() {

        if (context != null) {

            context.close();

        }

        if (browser != null) {

            browser.close();

        }

        if (playwright != null) {

            playwright.close();

        }

    }

}

The @BeforeEach method creates a new browser session and context for every test. The @AfterEach method closes the resources.

A separate context provides isolated cookies and browser storage for each test.

Step 2: Create LoginTest.java

package com.techsarvam.tests;

import com.techsarvam.base.BaseTest;

import com.techsarvam.config.Config;

import com.techsarvam.pages.LoginPage;

import com.techsarvam.testdata.TestData;

import com.microsoft.playwright.*;

import org.junit.jupiter.api.Test;

import java.nio.file.Files;

import java.nio.file.Paths;

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

public class LoginTest extends BaseTest {

    @Test

    void successfulLogin() throws Exception {

        LoginPage loginPage = new LoginPage(page);

        try {

            loginPage.open(Config.baseUrl());

            loginPage.enterUsername(TestData.USERNAME);

            loginPage.enterPassword(TestData.PASSWORD);

            loginPage.clickLogin();

            assertThat(

                page.getByRole(

                    com.microsoft.playwright.options.AriaRole.HEADING,

                    new Page.GetByRoleOptions().setName(“Dashboard”)

                )

            ).isVisible();

            context.tracing().stop();

        } catch (Exception e) {

            Files.createDirectories(Paths.get(“screenshots”));

            Files.createDirectories(Paths.get(“traces”));

            page.screenshot(

                new Page.ScreenshotOptions()

                    .setPath(Paths.get(“screenshots/login-failure.png”))

            );

            context.tracing().stop(

                new Tracing.StopOptions()

                    .setPath(Paths.get(“traces/login-failure.zip”))

            );

            throw e;

        }

    }

}

This example demonstrates a complete login workflow.

The test opens the login page, enters credentials, clicks the login button, and verifies that the Dashboard heading is visible.

The example assumes the application has accessible Username and Password labels and displays a Dashboard heading after successful login. Replace these values with the actual application locators and expected result.

The try-catch block saves a screenshot and trace when an exception occurs. In a larger framework, move failure-artifact handling into a reusable JUnit extension or test listener.

9. Advanced Framework Features

Cross-browser testing

Playwright supports Chromium, Firefox, and WebKit.

The Config class allows you to select a browser using a Maven system property.

Run Chromium:

mvn test -Dbrowser=chromium

Run Firefox:

mvn test -Dbrowser=firefox

Run WebKit:

mvn test -Dbrowser=webkit

You can also execute the same test suite in separate CI jobs for different browsers.

Parallel execution

JUnit 5 supports parallel test execution through its configuration.

Create src/test/resources/junit-platform.properties:

junit.jupiter.execution.parallel.enabled=true

junit.jupiter.execution.parallel.mode.default=same_thread

junit.jupiter.execution.parallel.mode.classes.default=concurrent

This configuration allows test classes to run concurrently while keeping methods within each class sequential.

Playwright objects should not be shared across threads without proper synchronization. Create a separate Playwright instance and browser context for each independent execution thread.

Environment configuration

Use system properties to execute tests against different environments.

mvn test -DbaseUrl=https://staging.example.com

This makes the framework reusable across development, QA, and staging environments.

10. Reporting and Debugging

Reporting helps automation engineers understand which tests passed or failed.

JUnit 5 works with Maven Surefire to generate test result files.

Execute:

mvn clean test

Maven generates test results under:

target/surefire-reports/

These reports include test execution information in text and XML formats.

For richer HTML reporting, integrate Allure with JUnit 5. Allure can display test results, attachments, steps, and execution details.

Screenshots

The login example captures a screenshot when an exception occurs.

Screenshots help identify:

  • Incorrect locators.
  • Unexpected application messages.
  • Navigation failures.
  • UI rendering problems.

Trace Viewer

Playwright tracing records browser activity, including screenshots and DOM snapshots.

Open a saved trace using:

mvn exec:java -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=”show-trace traces/login-failure.zip”

Trace Viewer helps investigate what happened before a failure.

Debugging techniques

Useful debugging options include:

Browser browser = playwright.chromium().launch(

    new BrowserType.LaunchOptions()

        .setHeadless(false)

        .setSlowMo(500)

);

Headed mode displays the browser window, while slowMo slows down browser actions to make debugging easier.

11. CI/CD Integration Using GitHub Actions

CI/CD allows automated tests to run whenever developers push code or create pull requests.

Create .github/workflows/playwright-java.yml.

name: Playwright Java Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – name: Checkout repository

        uses: actions/checkout@v4

      – name: Setup Java

        uses: actions/setup-java@v4

        with:

          distribution: temurin

          java-version: ’17’

          cache: maven

      – name: Install Playwright browsers

        run: >

          mvn exec:java

          -D exec.mainClass=com.microsoft.playwright.CLI

          -D exec.args=”install –with-deps chromium”

      – name: Run automation tests

        run: mvn clean test

      – name: Upload test results

        if: always()

        uses: actions/upload-artifact@v4

        with:

          name: playwright-java-results

          path: |

            target/surefire-reports/

            screenshots/

            traces/

The workflow checks out the project, configures Java, installs Chromium, and executes the JUnit tests.

For Jenkins, create a Pipeline with similar stages: checkout, configure JDK and Maven, install browser dependencies, execute mvn clean test, and archive test reports and failure artifacts.

12. Best Practices and Common Mistakes

Follow these practices when developing a Playwright framework with Java.

Best practiceWhy it matters
Use Page Object ModelImproves code reuse
Prefer role and label locatorsMakes tests easier to understand
Use Playwright assertionsSupports automatic retrying
Create separate contextsImproves test isolation
Close browser resourcesPrevents resource leaks
Manage test data separatelySimplifies maintenance
Use environment propertiesSupports multiple environments
Capture traces on failureHelps debugging

Common mistakes include:

  1. Writing all test logic inside one Java class.
  2. Using fixed waits instead of Playwright’s built-in waiting behavior.
  3. Sharing the same browser context across unrelated tests.
  4. Forgetting to close Playwright, browser, and context objects.
  5. Hardcoding production credentials.
  6. Running parallel tests with shared mutable state.
  7. Using fragile XPath expressions when accessible locators are available.
  8. Treating Playwright Java as if it uses the JavaScript Playwright Test runner.

Start with a small framework and introduce additional utilities and abstractions when the project needs them.

13. Interview Questions and FAQs

1. What is Playwright framework with Java?

It is a browser automation framework built using the official Playwright Java library and a Java test runner such as JUnit or TestNG.

2. What are the benefits of Playwright framework with Java?

It supports modern browser automation, reusable Java classes, multiple browsers, reliable locators, debugging, and integration with Maven and CI/CD tools.

3. Is Playwright framework with Java suitable for beginners?

Yes. Beginners with basic Java knowledge can learn browser navigation, locators, assertions, Page Object Model, and test execution step by step.

4. Does Playwright Java use Playwright Test?

No. Playwright Test is the built-in test runner for JavaScript and TypeScript. Java projects typically use JUnit or TestNG.

5. Can we use Page Object Model with Playwright Java?

Yes. Create a Java class for each application page and store its locators and reusable browser actions in that class.

6. How do you handle multiple browsers?

Use Playwright’s Chromium, Firefox, and WebKit browser types. Select the required browser through configuration or run separate CI jobs.

7. How do you capture screenshots?

Use the page.screenshot() method and specify a file path through Page.ScreenshotOptions.

8. How do you execute Playwright Java tests using Maven?

Use:

mvn clean test

Maven compiles the project and executes tests through the configured test runner.

Leave a Comment

Your email address will not be published. Required fields are marked *