1. Introduction
Playwright is a modern browser automation library developed by Microsoft. It allows automation testers to test web applications across Chromium, Firefox, and WebKit browsers.
Playwright Java provides browser automation APIs for Java developers. It supports end-to-end testing, functional testing, regression testing, and cross-browser testing.
JUnit is a popular Java testing framework used to organize and execute automated test scripts. It provides annotations, assertions, lifecycle methods, parameterized tests, and test execution features.
Combining Playwright Java with JUnit helps automation engineers build reusable and maintainable browser automation frameworks.
In this Playwright Java JUnit integration tutorial, you will learn how to create a Maven project, configure dependencies, initialize browsers, write your first test, implement a real-world login test, use parameterized tests, generate reports, and integrate your framework with CI/CD tools.
This guide is designed for freshers, Java automation testers, Selenium professionals, and aspiring SDETs who want to learn modern browser automation.
Important: Playwright Java is the official Java browser automation library. JUnit is the test runner used in this tutorial. This is different from Playwright Test, which is a separate test runner primarily used with Playwright’s Node.js ecosystem.
2. Prerequisites for Playwright Java JUnit Integration
Before starting the project, install the following tools.
| Tool | Recommended version | Purpose |
| Java JDK | 17 or later | Java application development |
| Apache Maven | 3.8+ | Dependency management |
| IntelliJ IDEA | Community or Ultimate | Java development |
| Playwright Java | 1.64.0 | Browser automation |
| JUnit Jupiter | 5.11.4 | Test execution |
| Chromium | Playwright-managed | Browser testing |
Verify Java installation
Open Command Prompt or Terminal:
java -version
Verify Maven installation
mvn -version
If Maven is missing, download it from the official Apache Maven website.
You should also understand basic Java programming, Maven dependencies, and browser automation concepts.
3. Playwright Java JUnit Project Setup Using Maven
Maven makes it easier to manage Playwright Java and JUnit dependencies.
Step 1: Create a Maven project
Open IntelliJ IDEA:
- Select File → New → Project.
- Choose Java.
- Select Maven as the build system.
- Choose JDK 17.
- Enter the project name PlaywrightJUnitProject.
- Click Create.
Alternatively, create the project through the terminal:
mvn archetype:generate \
-DgroupId=com.techsarvam \
-DartifactId=PlaywrightJUnitProject \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
Navigate to the project:
cd PlaywrightJUnitProject
Step 2: Add Playwright and JUnit dependencies
Open the pom.xml file and add the following complete configuration.
Complete Maven pom.xml
<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
<modelVersion>4.0.0</modelVersion>
<groupId>com.techsarvam</groupId>
<artifactId>PlaywrightJUnitProject</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.11.4</junit.version>
</properties>
<dependencies>
<!– Playwright Java –>
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.64.0</version>
</dependency>
<!– JUnit Jupiter –>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!– Java Compiler –>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<!– JUnit Test Execution –>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
<!– Playwright CLI –>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version>
</plugin>
</plugins>
</build>
</project>
Dependency explanation
| Dependency | Purpose |
| Playwright | Provides browser automation APIs |
| JUnit Jupiter | Provides JUnit 5 testing features |
| Maven Compiler | Compiles Java code |
| Maven Surefire | Executes automated tests |
| Exec Maven Plugin | Runs Playwright browser installation commands |
After saving pom.xml, reload the Maven project in IntelliJ IDEA.
Execute:
mvn clean install
Maven downloads the dependencies and compiles the project.
Step 3: Install Playwright browsers
Execute:
mvn exec:java -e \
-Dexec.mainClass=com.microsoft.playwright.CLI \
-Dexec.args=”install”
This installs the browser binaries compatible with the configured Playwright Java version.
For Linux CI environments, use:
mvn exec:java -e \
-Dexec.mainClass=com.microsoft.playwright.CLI \
-Dexec.args=”install –with-deps”
Playwright requires compatible browser binaries. Install them again when upgrading to a release that requires different browser revisions.
4. Playwright Java JUnit Project Folder Structure
A well-organized project structure makes automation scripts easier to maintain.
Recommended structure:
PlaywrightJUnitProject
│
├── pom.xml
│
├── src
│ ├── main
│ │ └── java
│ │ └── com/techsarvam
│ │ ├── pages
│ │ └── utilities
│ │
│ └── test
│ ├── java
│ │ └── com/techsarvam
│ │ ├── base
│ │ └── tests
│ │
│ └── resources
│ └── junit-platform.properties
│
└── target
└── surefire-reports
| Folder | Responsibility |
| pages | Page Object Model classes |
| utilities | Reusable helper methods |
| base | Browser setup and teardown |
| tests | JUnit test classes |
| resources | Test data and configuration |
| target | Compiled files and reports |
For enterprise automation projects, keep browser management, page objects, test data, and test cases separate.
5. Configure JUnit for Playwright Java
JUnit 5, also called JUnit Jupiter, provides annotations and lifecycle methods to organize automated tests.
Important JUnit annotations
| Annotation | Purpose |
| @Test | Marks a method as a test |
| @BeforeEach | Executes before every test |
| @AfterEach | Executes after every test |
| @BeforeAll | Executes once before all tests |
| @AfterAll | Executes once after all tests |
| @ParameterizedTest | Executes a test with multiple inputs |
| @ValueSource | Supplies simple test data |
| @CsvSource | Supplies multiple values per test |
| @Nested | Groups related test cases |
Example: JUnit lifecycle methods
package com.techsarvam.tests;
import org.junit.jupiter.api.*;
public class JUnitLifecycleTest {
@BeforeAll
static void beforeAll() {
System.out.println(“Starting test suite”);
}
@BeforeEach
void beforeEach() {
System.out.println(“Starting test”);
}
@Test
void testOne() {
System.out.println(“Executing test one”);
}
@Test
void testTwo() {
System.out.println(“Executing test two”);
}
@AfterEach
void afterEach() {
System.out.println(“Closing test”);
}
@AfterAll
static void afterAll() {
System.out.println(“Test suite completed”);
}
}
- @BeforeAll executes once.
- @BeforeEach executes before each test.
- JUnit executes the test methods.
- @AfterEach executes after each test.
- @AfterAll executes after all tests.
These lifecycle methods are useful for managing browser initialization, configuration, and cleanup.
6. Create Your First Playwright Java JUnit Test
Now let’s write a browser automation test using Playwright Java and JUnit.
Create FirstPlaywrightTest.java inside:
src/test/java/com/techsarvam/tests
package com.techsarvam.tests;
import com.microsoft.playwright.*;
import com.microsoft.playwright.assertions.PlaywrightAssertions;
import org.junit.jupiter.api.Test;
public class FirstPlaywrightTest {
@Test
void verifyWebsiteTitle() {
try (Playwright playwright =
Playwright.create()) {
Browser browser =
playwright.chromium().launch(
new BrowserType.LaunchOptions()
.setHeadless(true)
);
Page page = browser.newPage();
page.navigate(“https://playwright.dev”);
System.out.println(
“Website Title: ” + page.title()
);
PlaywrightAssertions.assertThat(page)
.hasTitle(“Fast and reliable end-to-end testing for modern web apps”);
browser.close();
}
}
}
Explanation
- Playwright.create() initializes Playwright.
- chromium().launch() launches Chromium.
- browser.newPage() creates a browser page.
- page.navigate() opens the website.
- page.title() retrieves the page title.
- PlaywrightAssertions.assertThat() validates the expected title.
- browser.close() closes the browser.
Playwright’s web-first assertions automatically retry until the expected condition is met or the assertion timeout expires.
Expected result: The test passes when the website title matches the expected title.
Execute the test using Maven
mvn test
To execute a particular test class:
mvn -Dtest=FirstPlaywrightTest test
Maven compiles the test and executes it using the JUnit Platform through Surefire.
7. Real-World Login Test Using Playwright Java JUnit
Let’s implement a practical login automation scenario.
We will use the demo website:
Demo credentials:
- Username: tomsmith
- Password: SuperSecretPassword!
Instead of repeating browser initialization in every test, create a reusable base class.
Step 1: Create BaseTest.java
package com.techsarvam.base;
import com.microsoft.playwright.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
public class BaseTest {
protected Playwright playwright;
protected Browser browser;
protected Page page;
@BeforeEach
void setUp() {
playwright = Playwright.create();
browser = playwright.chromium().launch(
new BrowserType.LaunchOptions()
.setHeadless(true)
);
page = browser.newPage();
}
@AfterEach
void tearDown() {
if (browser != null) {
browser.close();
}
if (playwright != null) {
playwright.close();
}
}
}
Step 2: Create LoginTest.java
package com.techsarvam.tests;
import com.techsarvam.base.BaseTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import com.microsoft.playwright.assertions.PlaywrightAssertions;
public class LoginTest extends BaseTest {
@Test
void verifySuccessfulLogin() {
page.navigate(
“https://the-internet.herokuapp.com/login”
);
page.locator(“#username”)
.fill(“tomsmith”);
page.locator(“#password”)
.fill(“SuperSecretPassword!”);
page.locator(“button[type=’submit’]”)
.click();
PlaywrightAssertions.assertThat(
page.locator(“.flash”)
).containsText(
“You logged into a secure area!”
);
assertEquals(
“Secure Area”,
page.locator(“h2”).innerText()
);
}
}
How does this test work?
| Step | Expected behavior |
| Open application | Login page loads |
| Enter username | Username is entered |
| Enter password | Password is entered |
| Click login | Application processes credentials |
| Verify message | Success message appears |
| Verify heading | Secure Area is displayed |
The base class manages browser resources, while the login test focuses on application behavior.
For production frameworks, move the login actions into a reusable LoginPage class and keep test verification in the test class. Also, use environment variables or a secrets manager instead of hardcoding credentials.
8. Advanced JUnit Features with Playwright Java
JUnit provides additional features that help build maintainable automation frameworks.
8.1 Parameterized tests
Parameterized tests allow you to execute the same test with different input values.
Add this example to a separate test class:
package com.techsarvam.tests;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import com.microsoft.playwright.*;
import static org.junit.jupiter.api.Assertions.*;
public class ParameterizedLoginTest {
@ParameterizedTest
@ValueSource(strings = {
“playwright”,
“selenium”,
“automation”
})
void verifySearchInput(String keyword) {
try (Playwright playwright =
Playwright.create()) {
Browser browser =
playwright.chromium().launch();
Page page = browser.newPage();
page.navigate(“https://playwright.dev”);
assertNotNull(keyword);
System.out.println(
“Testing keyword: ” + keyword
);
browser.close();
}
}
}
This example demonstrates parameterized execution with three values. In a real search test, use each supplied keyword to fill a search field and verify the results.
Other useful parameter sources include:
- @CsvSource: Supplies multiple values in CSV format.
- @MethodSource: Uses a Java method to provide test data.
- @EnumSource: Supplies enum values.
8.2 JUnit test suites
JUnit supports test suites through the JUnit Platform Suite API.
Add this dependency to pom.xml:
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite</artifactId>
<version>1.11.4</version>
<scope>test</scope>
</dependency>
package com.techsarvam.tests;
import org.junit.platform.suite.api.*;
@Suite
@SelectClasses({
FirstPlaywrightTest.class,
LoginTest.class
})
public class RegressionSuite {
}
This allows you to execute selected test classes together as a regression suite.
8.3 Parallel execution
JUnit supports parallel test execution through configuration.
Create:
src/test/resources/junit-platform.properties
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=concurrent
junit.jupiter.execution.parallel.mode.classes.default=concurrent
Each test should create its own Playwright, Browser, and Page instances. Do not share mutable browser objects between parallel tests.
Parallel execution can reduce test execution time, particularly for large regression suites, but make sure your test data and application environment also support concurrent execution.
8.4 Setup and teardown best practices
Use @BeforeEach and @AfterEach for test-level browser management.
For expensive shared resources, JUnit also provides @BeforeAll and @AfterAll. However, shared browser contexts can create test dependencies. Prefer isolated contexts when reliability is important.
9. Reporting and Debugging in Playwright Java JUnit
Reporting is important in automation testing because it helps QA engineers identify passed tests, failed tests, and execution errors.
Maven Surefire reports
Execute:
mvn clean test
Maven Surefire generates test reports inside:
target/
surefire-reports/
TEST-com.techsarvam.tests.LoginTest.xml
com.techsarvam.tests.LoginTest.txt
These reports contain test execution details and can be integrated with CI/CD reporting tools.
Generate HTML reports
Add the following plugin inside the plugins section of pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>3.5.2</version>
</plugin>
Execute:
mvn surefire-report:report
The HTML report will be generated at:
target/site/surefire-report.html
Capture screenshots
Screenshots are useful when a browser automation test fails.
page.screenshot(
new Page.ScreenshotOptions()
.setPath(Paths.get(“failure.png”))
);
Import:
import java.nio.file.Paths;
You can call this screenshot method from a JUnit extension or failure-handling method to capture evidence automatically.
Playwright Trace Viewer
Playwright tracing helps investigate browser interactions, page snapshots, and network activity.
context.tracing().start(
new Tracing.StartOptions()
.setScreenshots(true)
.setSnapshots(true)
.setSources(true)
);
After test execution:
context.tracing().stop(
new Tracing.StopOptions()
.setPath(Paths.get(“trace.zip”))
);
Create the BrowserContext explicitly before starting tracing. Save traces on failure and open them using the Playwright Trace Viewer.
10. CI/CD Integration with Playwright Java JUnit
In real-world projects, automation tests should execute automatically whenever developers push code changes.
You can integrate your Playwright Java JUnit Framework with Jenkins or GitHub Actions.
GitHub Actions integration
Create the workflow file:
.github/workflows/playwright-junit.yml
name: Playwright Java JUnit
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
– name: Checkout Code
uses: actions/checkout@v4
– name: Setup Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: ’17’
cache: maven
– name: Build Project
run: mvn clean install -DskipTests
– name: Install Playwright Browsers
run: >
mvn exec:java
-Dexec.mainClass=com.microsoft.playwright.CLI
-Dexec.args=”install –with-deps”
– name: Execute JUnit Tests
run: mvn test
– name: Upload Test Reports
if: always()
uses: actions/upload-artifact@v4
with:
name: junit-test-reports
path: target/surefire-reports/
Workflow explanation:
- GitHub checks out the automation project.
- Java 17 is configured.
- Maven downloads the dependencies.
- Playwright browsers and Linux dependencies are installed.
- JUnit test cases execute.
- Test reports are uploaded as workflow artifacts.
For Jenkins, configure JDK and Maven tools, install Playwright browser dependencies on the build agent, and execute:
mvn clean test
You can publish Surefire XML reports through Jenkins’ JUnit test reporting functionality.
11. Best Practices and Common Mistakes
Follow these practices when developing a professional automation framework.
| Best practice | Benefit |
| Use Page Object Model | Improves maintainability |
| Use separate browser contexts | Provides test isolation |
| Follow JUnit lifecycle methods | Manages browser resources |
| Use parameterized tests | Reduces duplicate scripts |
| Use Playwright assertions | Improves test reliability |
| Avoid Thread.sleep() | Reduces unnecessary waiting |
| Capture failure screenshots | Helps debugging |
| Use environment variables | Protects credentials |
| Enable parallel execution carefully | Reduces execution time |
| Integrate CI/CD | Automates regression testing |
- Sharing the same Page instance across parallel tests.
- Forgetting to close browser resources.
- Using fixed waits instead of Playwright auto-waiting.
- Hardcoding usernames and passwords.
- Keeping all automation code inside one test class.
- Using shared test data that causes parallel execution conflicts.
For enterprise frameworks, maintain reusable browser utilities, configuration files, logging, reporting, and test data management.
12. Frequently Asked Questions (FAQs)
1. What is Playwright Java JUnit integration?
Playwright Java JUnit integration means using the official Playwright Java library with JUnit to create and execute automated browser testing scripts.
Playwright handles browser automation, while JUnit manages test execution, lifecycle methods, and assertions.
2. What are the benefits of Playwright Java JUnit integration?
The major benefits include:
- Cross-browser testing.
- Reusable Java automation scripts.
- JUnit lifecycle management.
- Parameterized testing.
- Parallel test execution.
- Easy Maven integration.
- CI/CD compatibility.
3. Is Playwright Java JUnit integration suitable for beginners?
Yes. Beginners with basic Java knowledge can start with Playwright Java and JUnit.
Start with browser launch, navigation, locators, and assertions. Then learn Page Object Model, parameterized testing, reporting, and CI/CD.
4. Which dependency is required for Playwright Java?
The main Maven dependency is:
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.64.0</version>
</dependency>
5. How do you execute JUnit tests using Maven?
Execute:
mvn clean test
Maven compiles the project and runs tests using the Surefire plugin.
6. Can we use DataProvider with JUnit?
JUnit does not use TestNG’s @DataProvider. Instead, it provides @ParameterizedTest, @ValueSource, @CsvSource, and @MethodSource for data-driven testing.
7. Can Playwright Java JUnit tests run in parallel?
Yes. JUnit supports parallel execution through junit-platform.properties. Each parallel test should use independent browser resources.
8. What is the difference between JUnit and TestNG?
Both are Java testing frameworks. JUnit provides annotations, assertions, parameterized tests, and extensions. TestNG provides features such as DataProvider, groups, and XML-based suite configuration.
