Playwright Java Project Structure: Complete Framework Guide with Examples (2026)

1. Introduction

When automation engineers start working with Playwright Java, they often write all browser interactions, locators, test data, and assertions inside a single Java class.

This approach may work for a small automation exercise. However, when the project grows and contains hundreds of automated test scripts, maintaining everything in one class becomes difficult.

A well-designed Playwright Java project structure helps organize automation code into separate packages and files. It makes the framework easier to understand, maintain, reuse, and scale.

For example, consider an e-commerce application with login, registration, product search, shopping cart, and checkout functionality.

Instead of writing all automation logic in one class, you can organize it into:

  • Page classes for browser interactions.
  • Test classes for test scenarios.
  • Utilities for reusable operations.
  • Configuration files for environment settings.
  • Test data files for input values.
  • Reports for execution results.

Playwright Java is an official browser automation library for Java. It is different from Playwright Test, which is a separate test runner used in the JavaScript and TypeScript ecosystem.

In this tutorial, you will learn how to create a professional Playwright Java Maven project, implement Page Object Model, manage test data, configure browser setup, generate reports, and integrate your framework with CI/CD.

2. What Is Playwright Java Project Structure?

Playwright Java project structure refers to the organized arrangement of packages, Java classes, configuration files, test data, and resources used in a Playwright automation framework.

It defines where different parts of the automation code should be stored.

A good structure separates test execution from browser interactions and framework configuration.

Main components

ComponentResponsibility
TestsContains automated test scenarios
PagesContains page objects and locators
BaseManages browser and test lifecycle
UtilitiesProvides reusable helper methods
ConfigStores environment configuration
TestDataStores test input data
ResourcesContains properties, JSON, and XML files
ReportsStores execution results and debugging information

How the framework works

Test Classes

Test scenarios and assertions

Page Object Classes

Locators and page interactions

Playwright Java

Browser, context, and page management

Application Under Test

Web application

Configuration files, test data, utilities, and reporting support these layers.

3. Benefits of a Good Playwright Java Framework Structure

A well-organized framework provides several advantages.

BenefitExplanation
MaintainabilityChanges can be made in specific classes.
ReusabilityCommon browser actions can be reused.
ScalabilityNew modules can be added easily.
CollaborationMultiple automation engineers can work on separate modules.
ReadabilityDevelopers can understand the framework quickly.
DebuggingFailures are easier to investigate.
CI/CD integrationBuild and test execution become easier to manage.

For example, suppose the login button locator changes.

In a structured framework, you update it once in LoginPage.java. Every test using that page object automatically benefits from the change.

This reduces duplicate code and improves software quality assurance.

4. Prerequisites and Maven Setup

Before creating the project, install the required tools.

Prerequisites

ToolPurpose
JDK 17Java programming
MavenBuild and dependency management
IntelliJ IDEAJava development
Playwright JavaBrowser automation
JUnit 5Test execution
GitVersion control

Step 1: Create a Maven project

Create a Maven project named:

PlaywrightJavaFramework

Step 2: Configure pom.xml

Add the following dependencies:

<properties>

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

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

    <junit.version>5.13.4</junit.version>

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

</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-compiler-plugin</artifactId>

            <version>3.14.1</version>

        </plugin>

        <plugin>

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

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

            <version>3.5.4</version>

        </plugin>

    </plugins>

</build>

These are pinned example versions. Check compatibility with your Java and Maven environment before upgrading.

Step 3: Install dependencies and browsers

Run:

mvn clean install

Install Chromium:

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

The browser installation command requires the Maven Exec Plugin. Add this plugin to your pom.xml if you want to use the command above:

<plugin>

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

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

    <version>3.5.0</version>

</plugin>

For Linux CI environments, install browser dependencies with:

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

5. Recommended Playwright Java Project Folder Structure

Let’s create a practical Maven framework structure that can grow from a beginner project into an enterprise automation framework.

PlaywrightJavaFramework

│

├── pom.xml

├── README.md

├── .gitignore

│

├── src

│   ├── main

│   │   ├── java

│   │   │   └── com.techsarvam

│   │   │       ├── base

│   │   │       │   └── BasePage.java

│   │   │       │

│   │   │       ├── pages

│   │   │       │   └── LoginPage.java

│   │   │       │

│   │   │       ├── config

│   │   │       │   └── ConfigReader.java

│   │   │       │

│   │   │       └── utils

│   │   │           └── TestDataReader.java

│   │   │

│   │   └── resources

│   │       └── config.properties

│   │

│   └── test

│       ├── java

│       │   └── com.techsarvam.tests

│       │       ├── BaseTest.java

│       │       └── LoginTest.java

│       │

│       └── resources

│           └── testdata

│               └── login.json

│

└── target

    ├── surefire-reports

    ├── screenshots

    └── traces

Explanation of folders and files

Folder/fileResponsibility
pom.xmlManages Maven dependencies and plugins
baseContains reusable base page functionality
pagesContains page objects
configReads application configuration
utilsContains reusable helper methods
testsContains test classes
resourcesStores configuration and test data
testdataContains JSON or other input data
targetStores generated build and test outputs

Why use main and test folders?

The src/main/java folder contains reusable framework code, while src/test/java contains automated test classes.

This separation makes the project easier to maintain as the number of test cases increases.

The target directory is generated by Maven. It should not be manually maintained or committed to Git.

6. Creating Page Objects Using Page Object Model

Page Object Model (POM) is a design pattern that separates browser interactions from test scenarios.

Each application page has a corresponding Java class containing its locators and reusable actions.

For example, a login page should have a LoginPage.java class.

Create:

src/main/java/com/techsarvam/pages/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 url) {

        page.navigate(url);

    }

    public void enterUsername(String username) {

        page.locator(“[data-test=’username’]”)

            .fill(username);

    }

    public void enterPassword(String password) {

        page.locator(“[data-test=’password’]”)

            .fill(password);

    }

    public void clickLogin() {

        page.locator(“[data-test=’login-button’]”)

            .click();

    }

    public boolean isDashboardDisplayed() {

        return page.url().contains(“inventory.html”);

    }

}

Why use Page Object Model?

  • Locators are maintained in one place.
  • Browser interactions can be reused.
  • Test classes become shorter.
  • UI changes are easier to manage.
  • Multiple test cases can use the same page object.

For larger applications, create separate page classes such as:

pages/

    LoginPage.java

    HomePage.java

    ProductPage.java

    CartPage.java

    CheckoutPage.java

7. Organizing Test Classes

Test classes should contain test scenarios and assertions rather than repeated browser setup or locator definitions.

Use meaningful test class names.

Examples:

  • LoginTest.java
  • RegistrationTest.java
  • ProductSearchTest.java
  • CartTest.java
  • CheckoutTest.java

Create BaseTest.java

A base test class can manage browser initialization and cleanup.

Create:

src/test/java/com/techsarvam/tests/BaseTest.java

package com.techsarvam.tests;

import com.microsoft.playwright.*;

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();

        browser = playwright.chromium().launch(

            new BrowserType.LaunchOptions()

                .setHeadless(true)

        );

        context = browser.newContext();

        page = context.newPage();

    }

    @AfterEach

    void tearDown() {

        try {

            if (context != null) {

                context.close();

            }

            if (browser != null) {

                browser.close();

            }

        } finally {

            if (playwright != null) {

                playwright.close();

            }

        }

    }

}

Each JUnit test receives a new browser session. This is a simple and reliable approach for a beginner framework.

Why use BaseTest?

Without a base class, every test class may contain repeated browser initialization code.

By using BaseTest, you can centralize:

  • Browser launch configuration.
  • Browser context creation.
  • Page creation.
  • Resource cleanup.
  • Common test lifecycle operations.

For parallel execution, avoid sharing these mutable browser fields between test threads. Use independent per-thread resources and configure the test runner accordingly.

8. Managing Test Data and Configuration

A professional automation framework should not hardcode application URLs, usernames, passwords, and environment settings in every test class.

Use configuration files and external test data.

A. Create config.properties

Location:

src/main/resources/config.properties

baseUrl=https://www.saucedemo.com/

browser=chromium

headless=true

timeout=30000

B. Create ConfigReader.java

package com.techsarvam.config;

import java.io.InputStream;

import java.util.Properties;

public class ConfigReader {

    private static final Properties properties =

        new Properties();

    static {

        try (InputStream input =

            ConfigReader.class.getClassLoader()

                .getResourceAsStream(“config.properties”)) {

            if (input == null) {

                throw new IllegalStateException(

                    “config.properties not found”

                );

            }

            properties.load(input);

        } catch (Exception e) {

            throw new RuntimeException(

                “Unable to load configuration”, e

            );

        }

    }

    public static String get(String key) {

        return properties.getProperty(key);

    }

}

Now retrieve the application URL using:

String url = ConfigReader.get(“baseUrl”);

C. Create JSON test data

Location:

src/test/resources/testdata/login.json

{

  “username”: “standard_user”,

  “password”: “secret_sauce”

}

JSON is useful when multiple tests require different test data.

For larger projects, you can read JSON using Jackson or another JSON library.

Security note: Never store real production passwords or access tokens in committed test data files. Use environment variables or a secret manager.

9. Utilities and Reusable Framework Classes

Utilities contain common operations that can be reused across multiple test classes.

Examples include:

A simple screenshot utility:

ScreenshotUtil.java

package com.techsarvam.utils;

import com.microsoft.playwright.Page;

import java.nio.file.Paths;

public class ScreenshotUtil {

    public static void capture(

        Page page,

        String fileName) {

        page.screenshot(

            new Page.ScreenshotOptions()

                .setPath(

                    Paths.get(

                        “target/screenshots/” + fileName

                    )

                )

        );

    }

}

Create the screenshots directory before saving files:

new java.io.File(“target/screenshots”).mkdirs();

Keep utilities focused. Avoid creating a large generic helper class that contains unrelated methods.

10. Real-World Login Test Using the Project Structure

Now let’s connect the page object, configuration file, base test class, and test class.

We will use the SauceDemo practice application.

Step 1: Create LoginTest.java

Location:

src/test/java/com/techsarvam/tests/LoginTest.java

package com.techsarvam.tests;

import com.techsarvam.pages.LoginPage;

import com.techsarvam.config.ConfigReader;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class LoginTest extends BaseTest {

    @Test

    void validLoginTest() {

        LoginPage loginPage =

            new LoginPage(page);

        String url =

            ConfigReader.get(“baseUrl”);

        loginPage.open(url);

        loginPage.enterUsername(

            “standard_user”

        );

        loginPage.enterPassword(

            “secret_sauce”

        );

        loginPage.clickLogin();

        assertTrue(

            loginPage.isDashboardDisplayed(),

            “Dashboard was not displayed”

        );

        System.out.println(

            “Login test executed successfully”

        );

    }

}

Step 2: Understand the execution flow

  1. JUnit executes LoginTest.
  2. BaseTest launches Chromium.
  3. A browser context and page are created.
  4. ConfigReader retrieves the application URL.
  5. LoginPage performs browser interactions.
  6. JUnit validates the dashboard.
  7. BaseTest closes browser resources.

This demonstrates how different components of the Playwright Java project structure work together.

Step 3: Execute the test

Run:

mvn clean test

Expected output:

LoginTest

  validLoginTest PASSED

Tests run: 1

Failures: 0

Errors: 0

The test should navigate to the SauceDemo inventory page after successful login.

11. Reporting and Debugging

Reporting and debugging are essential for understanding automation execution results.

A professional Playwright Java framework should provide clear failure information.

A. Maven Surefire reports

The Maven Surefire plugin generates test reports automatically.

Report location:

target/surefire-reports/

These reports contain:

  • Number of tests executed.
  • Passed test cases.
  • Failed test cases.
  • Error information.
  • Execution details.

B. Screenshot on test failure

You can use JUnit 5’s TestWatcher extension to capture screenshots when tests fail.

Example:

import org.junit.jupiter.api.extension.*;

import com.techsarvam.utils.ScreenshotUtil;

public class ScreenshotExtension

        implements TestWatcher {

    private final BaseTest test;

    public ScreenshotExtension(BaseTest test) {

        this.test = test;

    }

    @Override

    public void testFailed(

        ExtensionContext context,

        Throwable cause) {

        if (test.page != null) {

            ScreenshotUtil.capture(

                test.page,

                context.getDisplayName() + “.png”

            );

        }

    }

}

For a complete implementation, register the extension in the test class and ensure the test lifecycle leaves the page available until the watcher runs. An alternative is to capture the screenshot directly in a test-specific failure handler.

C. Playwright Trace Viewer

Tracing helps investigate browser actions and failures.

Start tracing after creating the browser context:

context.tracing().start(

    new Tracing.StartOptions()

        .setScreenshots(true)

        .setSnapshots(true)

        .setSources(true)

);

Stop tracing before closing the context:

context.tracing().stop(

    new Tracing.StopOptions()

        .setPath(

            java.nio.file.Paths.get(

                “target/traces/login-trace.zip”

            )

        )

);

Create the target/traces directory before saving the trace.

Open the trace:

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

The Trace Viewer helps inspect browser actions, DOM snapshots, and network activity.

12. CI/CD Integration Using GitHub Actions

A good Playwright Java project structure should support continuous integration.

GitHub Actions can automatically execute Maven tests whenever code is pushed to a repository.

Create:

.github/workflows/playwright-tests.yml

name: Playwright Java Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  automation:

    runs-on: ubuntu-latest

    steps:

      – name: Checkout code

        uses: actions/checkout@v6

      – name: Setup Java

        uses: actions/setup-java@v5

        with:

          distribution: temurin

          java-version: ’17’

          cache: maven

      – name: Install dependencies

        run: mvn clean install -DskipTests

      – name: Install Playwright browsers

        run: >

          mvn exec:java

          -Dexec.mainClass=com.microsoft.playwright.CLI

          -Dexec.args=”install –with-deps chromium”

      – name: Execute tests

        run: mvn test

      – name: Upload reports

        if: always()

        uses: actions/upload-artifact@v4

        with:

          name: test-reports

          path: target/surefire-reports/

Jenkins integration

For Jenkins, configure:

  1. Source code repository.
  2. JDK 17.
  3. Maven installation.
  4. Browser dependencies.
  5. Maven execution command.

Use:

mvn clean test

You can publish Surefire reports using Jenkins test reporting features.

13. Best Practices and Common Mistakes

Follow these practices when designing a scalable automation framework.

Best practices

Best practiceRecommendation
Separation of concernsKeep tests, pages, and utilities separate
Naming conventionsUse meaningful class and method names
Reusable page objectsAvoid duplicate locators
External test dataKeep input data outside test logic
Configuration managementSupport multiple environments
Resource cleanupClose contexts and browsers
Failure debuggingCapture screenshots and traces
Version controlMaintain source code in Git
CI/CD integrationAutomate regression execution

Common mistakes

1. Writing everything in one class

This creates duplicate code and makes maintenance difficult.

2. Hardcoding environment URLs

Use properties files or environment variables to support development, QA, and staging environments.

3. Creating unnecessary base classes

Use inheritance only when it provides meaningful shared behavior. Do not build complex abstractions for a small project.

4. Sharing browser objects between parallel tests

Each parallel test should have independent Playwright resources and isolated browser contexts.

5. Committing generated reports

Keep target/, screenshots, traces, and other generated files out of source control unless there is a specific reason to retain them.

How to grow from beginner to enterprise framework

Project stageRecommended structure
BeginnerTests, Pages, BaseTest
IntermediateConfig, Utils, TestData, Reports
AdvancedAPI clients, logging, listeners, parallel execution
EnterpriseMulti-environment support, CI/CD, distributed execution, centralized reporting

Start with a simple framework and add components when actual project requirements demand them.

14. Interview Questions and FAQs

Practical interview questions

Q1. What is Playwright Java project structure?

It is the organized arrangement of Java packages, page objects, test classes, utilities, configuration files, and test data used in an automation framework.

Q2. Why do we use Page Object Model?

POM separates browser interactions and locators from test scenarios, improving reusability and maintainability.

Q3. What is the purpose of BaseTest.java?

It manages common test lifecycle operations such as browser initialization, context creation, page creation, and cleanup.

Q4. What is the purpose of config.properties?

It stores application settings such as base URL, browser type, and execution configuration.

Q5. Where should test data be stored?

Test data can be stored in JSON, CSV, Excel, or properties files under the test resources directory.

Q6. What is the difference between src/main/java and src/test/java?

src/main/java contains reusable framework code, while src/test/java contains automated test classes.

Q7. How do you manage browser cleanup?

Close the BrowserContext, Browser, and Playwright instances after each test.

Q8. How do you generate test reports?

Use Maven Surefire reports or integrate a reporting library such as Allure.

Q9. Can Playwright Java support parallel execution?

Yes. Use JUnit or TestNG parallel execution capabilities with independent Playwright resources per test thread.

Q10. What is the difference between Playwright Java and Playwright Test?

Playwright Java is a Java browser automation library. Playwright Test is a separate test runner designed for JavaScript and TypeScript.

Frequently asked questions

Q1. What is Playwright Java project structure?

It is a framework organization approach that separates test classes, page objects, utilities, configuration, test data, and reporting files.

Q2. How do I get started with Playwright Java project structure?

Install Java and Maven, create a Maven project, add Playwright Java and JUnit dependencies, create page and test packages, and implement a simple login test.

Q3. What are the benefits of Playwright Java project structure?

It improves maintainability, code reusability, scalability, team collaboration, debugging, and CI/CD integration.

Q4. Which design pattern is commonly used in Playwright Java frameworks?

Page Object Model is widely used to organize page locators and browser actions.

Q5. Is Maven required for Playwright Java?

No, but Maven is commonly used for dependency management, building projects, and running automated tests.

Leave a Comment

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