How to Automate a Login Page by Playwright Java




















How to Automate Login Page Using Playwright in Java (Complete Step-by-Step Guide)

Automating a login page is one of the most common and important tasks in test automation. Almost every web application starts with authentication, and ensuring that the login functionality works correctly is critical for application security and user experience.

In this detailed, SEO-optimized, AdSense-friendly guide, you will learn how to automate a login page using Playwright in Java, understand the conceptual workflow, and implement a real working example using the OrangeHRM demo website.

We will cover:

  • What is Playwright?

  • Why automate login functionality?

  • Step-by-step conceptual flow of login automation

  • Maven setup for Playwright Java

  • Complete Java code example

  • Code explanation in detail

  • Best practices for real-world projects

  • Positive and negative test validation strategies

  • Session handling and security considerations

Let’s begin.


What is Playwright?

Playwright is a modern, open-source automation framework developed by Microsoft. It allows you to automate:

  • Chromium (Chrome, Edge)

  • Firefox

  • WebKit (Safari engine)

Playwright supports multiple programming languages including Java, JavaScript, Python, and C#.

Key advantages of Playwright:

  • Auto-waiting mechanism

  • Fast execution

  • Built-in cross-browser support

  • Headless and headed execution

  • Network interception

  • API automation support

  • Powerful selectors

For Java automation engineers, Playwright provides a clean and robust API to simulate real user actions.


Why Automate a Login Page?

The login functionality is the entry point to most applications. Automating login ensures:

  • Credentials validation works properly

  • Role-based access is verified

  • Security messages appear correctly

  • Navigation to dashboard is successful

  • Application handles invalid login attempts properly

Login automation is usually reused across multiple test cases, so implementing it correctly is crucial.


Website Used for Automation

In this guide, we will automate the login page of the OrangeHRM demo application:

https://opensource-demo.orangehrmlive.com/web/index.php/auth/login

This demo website is widely used for automation practice and supports login with the following credentials:

  • Username: Admin

  • Password: admin123


Conceptual Flow of Login Automation in Playwright

When automating login using Playwright in Java, the process replicates the exact steps a real user performs.

Let’s understand the complete workflow conceptually.


1. Test Preparation

Launch Browser

First, Playwright launches a browser instance (Chromium, Firefox, or WebKit).

Create Browser Context

A browser context is like an isolated session (similar to incognito mode). It ensures:

  • No session overlap

  • Clean environment for each test

  • Independent cookies and storage

Create a Page

A Page represents a single browser tab where automation steps are executed.


2. Navigate to Login Page

The browser is directed to the login URL.

Playwright automatically waits for page load, but explicit waits can be added if required.


3. Interact with Input Fields

This involves:

  • Locating the username field

  • Locating the password field

  • Entering credentials using page.fill()

Selectors can be:

  • ID

  • Name

  • CSS

  • XPath

  • Placeholder

  • Role-based


4. Click Login Button

Once credentials are entered:

  • Locate the login button

  • Perform click action

  • Wait for navigation or page update

Playwright ensures the element is visible and actionable before clicking.


5. Handle Synchronization

After clicking login:

  • Application may redirect to dashboard

  • Page content changes dynamically

Playwright automatically waits for navigation events, but explicit waits like waitForSelector() can be used to ensure stability.


6. Validate Login

Positive Scenario

Verify a unique element on the dashboard such as:

  • Profile icon

  • Welcome message

  • Logout button

  • Dashboard heading

If visible → Login successful.

Negative Scenario

Enter incorrect credentials and verify:

  • Error message displayed

  • User remains on login page

  • Proper validation message appears


7. Security & Session Handling

Playwright allows:

  • Capturing cookies

  • Storing session storage

  • Reusing authentication state

Browser context ensures isolation so multiple tests do not share sessions.


8. Tear Down

After test execution:

  • Close page

  • Close browser context

  • Close browser

This ensures:

  • No memory leaks

  • Clean test environment

  • Stable execution


Step-by-Step Implementation

Now let’s implement login automation using Playwright Java.


Step 1: Add Maven Dependency

Add the following dependency in your pom.xml file:

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

After adding dependency, run:

mvn install

Also install browsers:

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


Step 2: Java Code to Automate Login

Below is the complete working code:

import com.microsoft.playwright.*; public class OrangeHRMLoginTest { public static void main(String[] args) { // Step 1: Launch Playwright try (Playwright playwright = Playwright.create()) { // Step 2: Launch a browser (Chromium) Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); // Step 3: Create a new browser context BrowserContext context = browser.newContext(); // Step 4: Open a new page Page page = context.newPage(); // Step 5: Navigate to the login page page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login"); // Step 6: Wait for username field page.waitForSelector("input[name='username']"); // Step 7: Fill login credentials page.fill("input[name='username']", "Admin"); page.fill("input[name='password']", "admin123"); // Step 8: Click login button page.click("button[type='submit']"); // Step 9: Wait for dashboard page.waitForSelector("h6.oxd-topbar-header-breadcrumb-module"); System.out.println("Login successful!"); // Step 10: Close browser browser.close(); } } }


Code Explanation (Detailed Breakdown)

Line/BlockExplanation
Playwright.create()Starts Playwright engine
chromium().launch()Launches Chromium browser
setHeadless(false)Opens browser in visible mode
browser.newContext()Creates isolated browser session
context.newPage()Opens new browser tab
page.navigate(url)Opens login page URL
waitForSelector()Waits until element is visible
page.fill()Enters text into input field
page.click()Clicks login button
browser.close()Closes browser


Required Credentials

For OrangeHRM demo:

  • Username: Admin

  • Password: admin123


Best Practices for Real-World Login Automation

To make your automation more stable and professional:

1. Avoid Hardcoding Credentials

Store credentials in:

  • Environment variables

  • Config file

  • Properties file


2. Use Explicit Assertions

Instead of just printing success message, validate:

if (page.isVisible("h6.oxd-topbar-header-breadcrumb-module")) { System.out.println("Login verified successfully"); }


3. Use Page Object Model (POM)

Create separate LoginPage class:

  • Define locators

  • Define login() method

This improves maintainability.


4. Add Negative Test Case

Test invalid login:

page.fill("input[name='username']", "WrongUser"); page.fill("input[name='password']", "WrongPass"); page.click("button[type='submit']"); page.waitForSelector(".oxd-alert-content-text");

Validate error message.


5. Use Headless Mode for CI/CD

For pipeline execution:

.setHeadless(true)

This improves speed and performance.


Handling Synchronization Properly

Although Playwright auto-waits:

  • Always wait for navigation when necessary

  • Use waitForSelector() for dynamic elements

  • Avoid Thread.sleep()

Proper synchronization ensures stable tests.


Security & Session Reuse

Playwright allows:

  • Saving storage state

  • Reusing authentication

Example:

context.storageState(new BrowserContext.StorageStateOptions().setPath("auth.json"));

This avoids repeated login in multiple tests.


Advantages of Using Playwright for Login Automation

  • Faster than Selenium

  • Auto-waiting built-in

  • Supports modern web apps

  • Easy API

  • Parallel execution support

  • Cross-browser testing


When to Integrate with Test Frameworks?

For enterprise projects, integrate with:

  • TestNG

  • JUnit

  • Cucumber (BDD)

This enables:

  • Reporting

  • Parallel execution

  • Suite management

  • CI/CD integration


Conclusion

Automating a login page using Playwright in Java is straightforward yet powerful. By simulating real user actions such as entering credentials and clicking login, you can verify authentication workflows effectively.

In this guide, we covered:

  • Conceptual flow of login automation

  • Maven setup

  • Complete Java implementation

  • Code explanation

  • Best practices

  • Positive and negative scenarios

  • Security and session handling

If you are building an automation framework, mastering login automation is the first and most important step.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. How to Show Visible Elements in Playwright

Integration of Playwright, Cucumber, and TestNG




Complete Guide to Integrating Cucumber, Playwright, and TestNG in Java (Step-by-Step Tutorial)

Modern test automation frameworks demand speed, scalability, readability, and maintainability. If you are working in automation testing or preparing for SDET roles, integrating Cucumber, Playwright, and TestNG in Java is one of the most powerful combinations you can learn today.

This detailed, fully SEO-optimized and AdSense-friendly guide explains:

  • What is Cucumber, Playwright, and TestNG?

  • Role of each tool in automation

  • How integration works step-by-step

  • Complete Maven configuration

  • Feature file implementation

  • Step definitions with Playwright

  • TestNG runner configuration

  • Parallel execution setup

  • Benefits of this integration

  • Real-time project structure

By the end of this guide, you will clearly understand how to build a professional BDD automation framework using Java.


What is Cucumber, Playwright, and TestNG Integration?

Integrating Cucumber, Playwright, and TestNG in Java enables you to:

  • Write BDD-style test cases using Gherkin (.feature files)

  • Automate browser actions using Playwright

  • Manage execution using TestNG

  • Generate structured and readable reports

This combination is widely used in enterprise-level automation frameworks because it ensures:

  • Clean architecture

  • Collaboration between business and QA teams

  • Cross-browser testing

  • Parallel execution support

  • Advanced reporting capabilities


Role of Each Component in the Framework

Let’s understand the purpose of each tool clearly.


1. Playwright – The Browser Automation Engine

Playwright is a modern browser automation framework that supports:

  • Chromium

  • Firefox

  • WebKit

Playwright is responsible for:

  • Launching browsers

  • Navigating web pages

  • Clicking elements

  • Entering text

  • Handling alerts

  • Capturing screenshots

  • Validating UI elements

  • Performing cross-browser testing

It provides fast and reliable execution with auto-waiting features and modern selector strategies.

In simple words:

👉 Playwright performs actual browser operations.


2. Cucumber – The BDD Framework

Cucumber is a Behavior-Driven Development (BDD) framework that allows writing test scenarios in Gherkin language.

Gherkin format:

  • Given

  • When

  • Then

  • And

  • But

Example:

Given user launches the browser When user logs in with valid credentials Then homepage should be displayed

Benefits of Cucumber:

  • Makes test cases readable

  • Bridges gap between business and technical teams

  • Allows non-technical stakeholders to understand test scenarios

  • Encourages collaboration

In simple words:

👉 Cucumber defines what needs to be tested in plain English.


3. TestNG – The Test Execution Framework

TestNG is a powerful Java testing framework that provides:

  • Test configuration

  • Annotations (@Before, @After, etc.)

  • Parallel execution

  • Grouping tests

  • Data-driven testing

  • Detailed reporting

  • Retry mechanisms

TestNG controls:

  • How tests run

  • In what order they run

  • Whether they run in parallel

  • How reports are generated

In simple words:

👉 TestNG manages execution and reporting.


How Cucumber + Playwright + TestNG Integration Works

Let’s understand the flow step-by-step.


Step 1: Cucumber Defines Test Scenarios

Business or QA teams write scenarios inside feature files using Gherkin syntax.

Example:

Feature: Check title Scenario: Open login page and check title Given I launch the application Then I should see the page title as "Example Domain"

These feature files describe expected behavior.


Step 2: Step Definitions Use Playwright

Each Gherkin step is mapped to a Java method called Step Definition.

Inside these step definitions:

  • Playwright APIs are used.

  • Browser actions are performed.

  • Assertions validate results.

For example:

  • page.navigate()

  • page.title()

  • page.click()

Playwright executes real browser interactions.


Step 3: TestNG Executes Scenarios

TestNG acts as the test runner.

It:

  • Executes Cucumber feature files

  • Controls parallel execution

  • Generates execution reports

  • Integrates with Maven

TestNG can run scenarios in parallel using DataProvider.


Step 4: Unified Reporting

After execution:

  • Cucumber generates BDD-style reports.

  • TestNG generates execution reports (HTML/XML).

  • Reports can be integrated with advanced tools like Allure or Extent Reports.

This ensures:

  • Business-friendly reports

  • Developer-friendly logs


Tools Used in This Framework

  • Cucumber for BDD feature files

  • Playwright for Java for browser automation

  • TestNG for execution and reporting

  • Maven for dependency management

Website to be automated:

https://example.com


Step-by-Step Integration Setup

Let’s implement a simple example that verifies the title of https://example.com.


1. pom.xml Configuration

The pom.xml file manages project dependencies.

<project> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>cucumber-playwright-testng</artifactId> <version>1.0</version> <dependencies> <!-- Cucumber Dependencies --> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-java</artifactId> <version>7.14.0</version> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-testng</artifactId> <version>7.14.0</version> </dependency> <!-- TestNG --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.9.0</version> <scope>test</scope> </dependency> <!-- Playwright Java --> <dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <configuration> <suiteXmlFiles> <suiteXmlFile>testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> </plugins> </build> </project>

This configuration connects all tools together.


2. Feature File (Title.feature)

Location:

src/test/resources/features/Title.feature

Feature: Check title Scenario: Open login page and check title Given I launch the application Then I should see the page title as "Example Domain"

This describes expected behavior in simple English.


3. PlaywrightFactory.java

This utility class manages:

  • Playwright object

  • Browser instance

  • Page instance

  • Initialization

  • Cleanup

package utils; import com.microsoft.playwright.*; public class PlaywrightFactory { public static Playwright playwright; public static Browser browser; public static Page page; public static void init() { playwright = Playwright.create(); browser = playwright.chromium().launch( new BrowserType.LaunchOptions().setHeadless(false) ); page = browser.newPage(); } public static void close() { browser.close(); playwright.close(); } }

Why use a factory class?

  • Avoid duplicate code

  • Centralize browser management

  • Improve maintainability


4. Step Definition Class (LoginSteps.java)

This class connects feature steps to Playwright actions.

package steps; import com.microsoft.playwright.Page; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.en.*; import utils.PlaywrightFactory; import static org.testng.Assert.assertEquals; public class LoginSteps { Page page; @Before public void setup() { PlaywrightFactory.init(); page = PlaywrightFactory.page; } @Given("I launch the application") public void i_launch_the_application() { page.navigate("https://example.com"); } @Then("I should see the page title as {string}") public void i_should_see_the_page_title_as(String expectedTitle) { String actualTitle = page.title(); assertEquals(actualTitle, expectedTitle); } @After public void tearDown() { PlaywrightFactory.close(); } }

Execution flow:

  • @Before initializes browser

  • Given step navigates to site

  • Then step validates title

  • @After closes browser


5. TestRunner.java (Cucumber + TestNG Runner)

package runners; import io.cucumber.testng.AbstractTestNGCucumberTests; import io.cucumber.testng.CucumberOptions; import org.testng.annotations.DataProvider; @CucumberOptions( features = "src/test/resources/features", glue = "steps", plugin = {"pretty", "html:target/cucumber-reports.html"}, monochrome = true ) public class TestRunner extends AbstractTestNGCucumberTests { @Override @DataProvider(parallel = true) public Object[][] scenarios() { return super.scenarios(); } }

Important points:

  • features → Location of feature files

  • glue → Location of step definitions

  • plugin → Reporting configuration

  • DataProvider(parallel = true) → Enables parallel execution


6. testng.xml (Optional Suite Execution)

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="Cucumber Playwright TestNG Suite"> <test name="Cucumber Tests"> <classes> <class name="runners.TestRunner"/> </classes> </test> </suite>

This file allows suite-level control and execution.


Advantages of This Integration

1. Readable Test Scenarios

Cucumber makes scenarios easy to understand.

2. Powerful Browser Automation

Playwright ensures fast and reliable execution.

3. Parallel Execution

TestNG allows parallel execution for faster test cycles.

4. Scalability

This framework works well for:

  • Large enterprise projects

  • Continuous Integration pipelines

  • Multi-browser testing

5. Flexible Reporting

Both:

  • BDD reports

  • Technical execution reports

are generated.


Best Practices for Enterprise Projects

  • Use Page Object Model (POM)

  • Avoid hardcoded URLs

  • Store configurations in properties file

  • Use proper logging

  • Implement retry logic

  • Integrate with CI/CD tools


Conclusion

Integrating Cucumber, Playwright, and TestNG in Java creates a powerful, scalable, and maintainable automation framework.

Cucumber provides readability.
Playwright provides modern browser automation.
TestNG provides execution control and reporting.

This combination is ideal for:

  • Automation testers

  • SDET engineers

  • QA leads

  • Enterprise automation frameworks

If you are building a real-world automation project, this integration is highly recommended.