Showing posts with label #RESTAPI. Show all posts
Showing posts with label #RESTAPI. Show all posts

Friday, July 24, 2026

Playwright File Upload, Download & Drag-and-Drop Automation Using Java (Complete Guide)

Introduction

Modern web applications frequently require users to upload documents, download reports, or drag and drop files between different sections of the application.

Examples include:

  • Uploading profile pictures
  • Importing Excel spreadsheets
  • Downloading invoices or reports
  • Uploading resumes in job portals
  • Attaching files in support tickets
  • Dragging files into cloud storage applications

Automating these scenarios reliably is an essential skill for every automation engineer.

In this tutorial, you'll learn how to automate file uploads, file downloads, and drag-and-drop functionality using Playwright with Java.


Why File Handling Automation is Important

Many business-critical workflows depend on files.

Examples include:

  • Banking statement uploads
  • Insurance document verification
  • HR resume uploads
  • Medical report downloads
  • Invoice generation
  • Tax document processing

Automating these scenarios improves regression coverage and reduces manual effort.


Project Setup

Ensure your project includes the Playwright dependency.

<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.55.0</version>
</dependency>

Understanding File Upload in Playwright

Unlike Selenium, Playwright does not interact with the operating system's native file chooser.

Instead, it directly uploads files using the input element.

This makes uploads faster and more reliable.


Upload a Single File

Example:

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

page.setInputFiles(
    "input[type='file']",
    Paths.get("files/resume.pdf")
);

The selected file is uploaded immediately after it is assigned to the input element.


Upload Multiple Files

Some applications allow users to upload several files simultaneously.

page.setInputFiles(
    "input[type='file']",
    new Path[] {
        Paths.get("files/report.pdf"),
        Paths.get("files/image.png"),
        Paths.get("files/data.xlsx")
    }
);

Playwright uploads all selected files in one operation.


Remove Uploaded Files

To clear a previously selected file:

page.setInputFiles(
    "input[type='file']",
    new Path[] {}
);

This resets the file input field.


Handling Hidden File Inputs

Some applications hide the HTML file input and trigger it using a button.

Playwright can still upload files because it interacts directly with the input element.

Locate the hidden input and call:

page.setInputFiles(
    "#hiddenFileInput",
    Paths.get("files/document.pdf")
);

No JavaScript execution is required.


Working with File Chooser

Some websites open the file chooser after clicking a button.

Example:

FileChooser chooser =
    page.waitForFileChooser(() -> {

        page.click("#uploadButton");

    });

chooser.setFiles(
    Paths.get("files/profile.png")
);

Playwright waits for the chooser and then selects the file programmatically.


Downloading Files

Playwright provides built-in support for file downloads.

Example:

Download download =
    page.waitForDownload(() -> {

        page.click("#downloadReport");

    });

The Download object provides information about the downloaded file.


Save Downloaded File

Store the downloaded file in a specific directory.

download.saveAs(
    Paths.get(
        "downloads/report.pdf"
    )
);

This makes it easy to validate downloaded reports or archive test artifacts.


Verify Download

After saving the file, verify its existence.

Path path =
    Paths.get("downloads/report.pdf");

assert Files.exists(path);

You can also verify:

  • File name
  • File size
  • File extension
  • File content
  • Creation date

Drag and Drop

Many modern applications use drag-and-drop interactions.

Examples include:

  • Trello boards
  • Kanban applications
  • Cloud storage systems
  • Dashboard widgets

Playwright simplifies these actions.

page.dragAndDrop(
    "#source",
    "#target"
);

This performs the complete drag-and-drop interaction.


Drag Files into Upload Areas

Many websites support dragging files into a drop zone.

Typical flow:

  1. User selects a file.
  2. User drags it over the drop zone.
  3. Application uploads the file automatically.

In Playwright, this is usually implemented by uploading through the underlying file input element associated with the drop zone.


Validate Upload Success

Always verify that the upload completed successfully.

Example:

assertThat(
    page.locator(".success-message")
).containsText("Upload completed");

Validation is more reliable than assuming the upload succeeded.


Organizing Test Files

Store reusable files in a dedicated directory.

Example:

src

└── test

    └── resources

        └── testdata

            ├── sample.pdf

            ├── image.png

            ├── resume.docx

            └── report.xlsx

This structure keeps your project clean and portable.


Common Upload Challenges

File Size Restrictions

Applications may reject files larger than the allowed limit.

Test:

  • Small files
  • Large files
  • Boundary values

Unsupported File Types

Validate that unsupported formats produce appropriate validation messages.

Example:

  • Upload .exe
  • Upload .zip
  • Upload .bat

Verify that the application blocks invalid uploads.


Duplicate Uploads

Ensure the application correctly handles repeated uploads of the same file.


Interrupted Uploads

Test behavior during:

  • Network interruptions
  • Session expiration
  • Browser refresh
  • Upload cancellation

Best Practices

Store Test Files in Version Control

Keep sample files inside the project so that all team members use the same test data.


Use Relative Paths

Avoid absolute paths such as:

C:\Users\John\Desktop\file.pdf

Instead, use project-relative paths to improve portability.


Verify Download Content

Checking only the file name is insufficient.

Validate:

  • Content
  • Size
  • Format
  • Generated values

Keep Test Files Small

Large files increase execution time and repository size.

Use compact sample files unless testing file size limits.


Clean Up Download Directories

Delete temporary files after execution to prevent unnecessary storage growth.


Common Interview Questions

How does Playwright upload files?

Playwright uploads files by assigning them directly to the HTML file input element using setInputFiles(), without interacting with the native operating system file picker.


Can Playwright upload multiple files?

Yes. Pass an array of Path objects to setInputFiles().


How do you verify a downloaded file?

Save the file using download.saveAs() and validate its existence, size, name, or contents.


Does Playwright support drag-and-drop?

Yes. The dragAndDrop() method performs drag-and-drop interactions between source and target elements.


Why use relative file paths?

Relative paths make the framework portable across different operating systems, developers' machines, and CI/CD environments.


Conclusion

File handling is a critical aspect of end-to-end web automation.

Playwright provides simple and reliable APIs for uploading files, downloading reports, handling file chooser dialogs, and automating drag-and-drop interactions.

In this guide, you learned how to:

  • Upload single and multiple files
  • Handle hidden file inputs
  • Work with the file chooser
  • Download and verify files
  • Perform drag-and-drop actions
  • Organize test resources
  • Apply enterprise best practices

By mastering these techniques, you'll be able to automate many real-world business workflows involving documents, reports, and media files with confidence.

Wednesday, July 22, 2026

Playwright Authentication Handling (Basic Auth, OAuth, JWT & Session Management) Using Java

Introduction

Authentication is one of the first challenges automation engineers face when testing modern web applications. Whether you're working with an internal enterprise application, an e-commerce platform, or a cloud-based SaaS product, your tests often need to log in before performing business operations.

Repeatedly logging in before every test slows execution and increases maintenance. Playwright provides several mechanisms to handle authentication efficiently, including Basic Authentication, OAuth flows, JWT tokens, cookies, and session reuse.

In this guide, you'll learn the most common authentication techniques used in Playwright with Java and when to use each approach.


Why Authentication Matters in Automation

Authentication enables secure access to protected resources and user-specific functionality.

Common authentication methods include:

  • Username and password
  • HTTP Basic Authentication
  • OAuth 2.0
  • JWT (JSON Web Tokens)
  • Session cookies
  • Single Sign-On (SSO)

A good automation framework should support all of these without duplicating login logic across tests.


HTTP Basic Authentication

Basic Authentication sends a username and password with every request.

Playwright supports it during browser context creation.

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setHttpCredentials(
                "admin",
                "password123"
            )
    );

Page page = context.newPage();

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

This is commonly used for internal tools or protected staging environments.


Form-Based Login

Most applications use login forms.

Example:

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

page.fill("#username", "admin");

page.fill("#password", "password123");

page.click("#loginButton");

page.waitForURL("**/dashboard");

Playwright automatically waits for navigation and element readiness.


Reusing Logged-In Sessions

Logging in before every test increases execution time.

Instead, log in once and reuse the authenticated session.

After a successful login:

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

This saves cookies and local storage to a file.


Loading a Saved Session

Reuse the saved session in future tests.

BrowserContext context =
    browser.newContext(
        new Browser.NewContextOptions()
            .setStorageStatePath(
                Paths.get("storageState.json")
            )
    );

Page page = context.newPage();

This allows tests to start in an authenticated state without repeating the login process.


Working with Cookies

Applications often use cookies to maintain user sessions.

Retrieve cookies:

List<BrowserContext.Cookie> cookies =
        context.cookies();

System.out.println(cookies.size());

You can also inspect individual cookie properties for debugging or validation.


Adding Cookies Manually

Sometimes it's useful to inject cookies directly.

BrowserContext.Cookie cookie =
        new BrowserContext.Cookie();

cookie.setName("sessionId");
cookie.setValue("ABC123");
cookie.setDomain("example.com");
cookie.setPath("/");

context.addCookies(
        List.of(cookie)
);

This is useful when preparing pre-authenticated sessions.


JWT Token Authentication

Many REST APIs and Single Page Applications (SPAs) use JSON Web Tokens.

You can send a JWT token in request headers.

APIRequestContext request =
    playwright.request().newContext(
        new APIRequest.NewContextOptions()
            .setExtraHTTPHeaders(
                Map.of(
                    "Authorization",
                    "Bearer YOUR_JWT_TOKEN"
                )
            )
    );

This approach is common for API testing and backend integration.


OAuth Authentication

OAuth is widely used for social login providers such as:

  • Google
  • Microsoft
  • GitHub
  • LinkedIn

The typical flow is:

  1. User clicks Sign in.
  2. Browser redirects to the identity provider.
  3. User authenticates.
  4. Identity provider redirects back with an authorization code or token.

Automating OAuth directly can be complex because it often involves multi-factor authentication or third-party security policies.

In enterprise environments, a common practice is to authenticate once and reuse the saved session instead of repeating the entire OAuth flow.


API Login for Faster Tests

Instead of logging in through the UI, authenticate using an API and then open the browser with the authenticated session.

Typical flow:

  1. Send login API request.
  2. Receive session token or cookie.
  3. Save authentication data.
  4. Launch browser using the authenticated state.

This reduces execution time and avoids repetitive UI interactions.


Handling Session Expiration

Sessions may expire during long-running test suites.

To avoid failures:

  • Refresh the session when necessary.
  • Regenerate authentication tokens.
  • Recreate the storage state periodically.
  • Monitor token expiration times.

Multi-User Testing

Enterprise applications often require testing with multiple roles.

Example roles:

  • Administrator
  • Manager
  • Employee
  • Customer

Create a separate storage state file for each role.

storage/

├── admin.json

├── manager.json

├── employee.json

This keeps user sessions isolated and easy to manage.


Secure Credential Management

Never hardcode usernames or passwords in source code.

Instead, use:

  • Environment variables
  • Configuration files
  • Secret management tools
  • CI/CD pipeline secrets

This improves security and simplifies maintenance.


Best Practices

Reuse Sessions

Save authenticated sessions and reuse them whenever possible.

This significantly reduces test execution time.


Prefer API Login

When available, use backend authentication APIs instead of UI login for setup.


Isolate User Sessions

Each test should use its own browser context and session data.

Avoid sharing authenticated contexts across parallel tests.


Rotate Test Accounts

Use dedicated automation accounts and reset their state regularly to prevent unexpected failures.


Monitor Authentication Failures

Log authentication errors clearly so that expired credentials or configuration issues are easy to identify.


Common Interview Questions

What is storageState in Playwright?

storageState saves cookies and local storage so that authenticated sessions can be reused in later tests.


Why reuse authenticated sessions?

It speeds up execution, reduces repeated login operations, and improves test stability.


Can Playwright automate OAuth?

Yes, but many OAuth providers use additional security mechanisms such as MFA. In practice, teams often authenticate once and reuse the saved session.


How do you authenticate API requests using JWT?

Include the JWT token in the Authorization header using the Bearer scheme.


Why shouldn't credentials be hardcoded?

Hardcoded credentials create security risks and make maintenance more difficult. Externalized configuration is the recommended approach.


Conclusion

Authentication is a foundational aspect of web automation.

Playwright provides flexible options for handling Basic Authentication, form-based login, OAuth, JWT tokens, cookies, and reusable sessions, enabling automation engineers to build secure, fast, and maintainable test frameworks.

In this guide, you learned how to:

  • Implement HTTP Basic Authentication
  • Automate form-based login
  • Save and reuse authenticated sessions
  • Work with cookies
  • Authenticate API requests using JWT
  • Understand OAuth automation strategies
  • Apply enterprise authentication best practices

By mastering these techniques, you'll build automation suites that execute faster, scale more effectively, and align with the authentication patterns used in modern enterprise applications.

Monday, July 20, 2026

Playwright Network Interception and API Mocking with Java (Complete Guide)

Introduction

Modern web applications communicate extensively with backend services through REST APIs. Every time you log in, search for products, submit forms, or load dashboards, your browser sends multiple HTTP requests behind the scenes.

Traditionally, UI automation relied on live backend services, making tests slow and vulnerable to network issues. Playwright changes this by allowing you to intercept network traffic, modify requests, mock responses, and even simulate server failures—all from your test code.

In this guide, you'll learn how to use Playwright's network interception and API mocking capabilities with Java to build faster, more reliable automation tests.


What is Network Interception?

Network interception allows you to inspect or control HTTP requests made by the browser during test execution.

You can:

  • Observe outgoing requests
  • Modify request headers
  • Change request payloads
  • Mock API responses
  • Abort requests
  • Simulate backend failures
  • Improve test reliability

Why Use API Mocking?

API mocking allows frontend testing even when backend services are:

  • Still under development
  • Temporarily unavailable
  • Returning inconsistent data
  • Difficult to reproduce specific scenarios
  • Rate limited

Instead of calling the real server, Playwright returns a predefined response.

Benefits include:

  • Faster execution
  • Stable tests
  • Repeatable scenarios
  • Easier edge-case testing

Understanding Playwright Routes

Playwright uses the route() method to intercept requests.

Basic syntax:

page.route("**/*", route -> {

    route.continue_();

});

This intercepts every request and allows it to continue normally.


Intercept a Specific API Request

Suppose the application calls:

GET /api/users

Intercept only that endpoint:

page.route("**/api/users", route -> {

    route.continue_();

});

Other requests continue without interception.


Block Images to Speed Up Tests

Large images increase page load time.

Block them during automation:

page.route("**/*.{png,jpg,jpeg,gif}", route -> {

    route.abort();

});

Benefits:

  • Faster execution
  • Lower bandwidth usage
  • Reduced memory consumption

Mock an API Response

Instead of calling the real server:

page.route("**/api/users", route -> {

    route.fulfill(

        new Route.FulfillOptions()

            .setStatus(200)

            .setContentType("application/json")

            .setBody("""
                [
                  {
                    "id":1,
                    "name":"John Doe"
                  }
                ]
            """)
    );

});

The application receives the mocked response immediately.


Mock an Error Response

Testing error handling is easy.

Example:

page.route("**/api/users", route -> {

    route.fulfill(

        new Route.FulfillOptions()

            .setStatus(500)

            .setBody("Internal Server Error")

    );

});

Now you can verify whether the application displays the correct error message.


Simulate Network Failure

To simulate a server outage:

page.route("**/api/users", route -> {

    route.abort();

});

This allows you to validate retry logic and offline behavior.


Modify Request Headers

You can add or replace HTTP headers.

page.route("**/api/users", route -> {

    Map<String, String> headers =
        new HashMap<>(route.request().headers());

    headers.put("X-Test-User", "Automation");

    route.resume(

        new Route.ResumeOptions()
            .setHeaders(headers)

    );

});

Useful for testing feature flags or custom authentication.


Modify POST Request Data

Intercept a request before it reaches the server.

page.route("**/api/orders", route -> {

    System.out.println(
        route.request().postData()
    );

    route.continue_();

});

This helps verify request payloads during automation.


Log Network Requests

Monitor all requests:

page.onRequest(request ->

    System.out.println(
        request.method() + " " + request.url()

    )
);

Useful for debugging complex applications.


Log Network Responses

Capture server responses:

page.onResponse(response ->

    System.out.println(

        response.status() +

        " " +

        response.url()

    )
);

This helps identify failed API calls.


Wait for a Specific Response

Instead of using delays:

page.waitForResponse(

    "**/api/users"

);

This ensures the test proceeds only after the required response is received.


Verify API Response Status

Example:

page.onResponse(response -> {

    if (response.url().contains("/users")) {

        System.out.println(

            response.status()

        );

    }

});

You can also validate response headers or body content.


Practical Scenario

Imagine an e-commerce application.

Flow:

  1. User searches for a product.
  2. Frontend calls:
/api/search
  1. Instead of calling the real backend, Playwright returns:
[
  {
    "product":"Laptop",
    "price":899
  }
]

The UI behaves exactly as if the backend had returned the data.

This approach enables testing even when backend systems are unavailable.


Best Practices

Mock Only What Is Necessary

Avoid mocking every request.

Use real backend services when integration testing is required.

Mock only external or unstable dependencies.


Keep Mock Data Realistic

Use responses that resemble production data.

Include:

  • IDs
  • Dates
  • Nested objects
  • Validation messages

This improves test quality.


Separate Mock Files

Store large mock responses in JSON files instead of embedding them in Java code.

Example:

src

└── test

    └── resources

        └── mocks

            ├── users.json

            ├── products.json

            └── orders.json

Log Requests During Debugging

Request and response logging simplifies troubleshooting.

Disable verbose logging in production pipelines unless needed.


Combine with API Tests

Use Playwright's built-in API testing features alongside network interception to create comprehensive end-to-end automation.


Common Interview Questions

What is network interception in Playwright?

Network interception allows tests to inspect, modify, block, or mock HTTP requests and responses during browser automation.


What is API mocking?

API mocking replaces real backend responses with predefined data, enabling reliable frontend testing without depending on live services.


Can Playwright block network requests?

Yes. The route.abort() method can block requests such as images, analytics scripts, or API calls.


Why use mocked APIs?

Mocked APIs make tests faster, more stable, and easier to execute when backend services are unavailable or difficult to control.


How do you wait for a specific network response?

Use page.waitForResponse() to synchronize test execution with a specific HTTP response.


Conclusion

Network interception and API mocking are among Playwright's most powerful capabilities.

They enable you to build faster, more reliable, and more maintainable automation suites by reducing dependency on external services and allowing precise control over browser communication.

In this guide, you learned how to:

  • Intercept network requests
  • Mock API responses
  • Modify headers and request payloads
  • Block unwanted resources
  • Simulate server failures
  • Wait for network responses
  • Apply enterprise best practices

Mastering these techniques will help you create robust automation frameworks capable of testing complex applications under a wide variety of real-world conditions.

Thursday, July 9, 2026

Playwright Reporting with Allure Reports Using Java (Complete Step-by-Step Guide)

Automation testing is not just about executing test cases—it's also about presenting the results in a clear and meaningful way. While TestNG provides basic HTML reports, enterprise teams often use Allure Reports because they offer interactive dashboards, screenshots, execution history, attachments, and detailed failure analysis.

In this guide, you'll learn how to integrate Allure Reports with Playwright using Java and TestNG.


Why Use Allure Reports?

Allure Reports provide:

  • Interactive HTML reports
  • Test execution history
  • Test categorization
  • Screenshots for failed tests
  • Video attachments
  • Environment information
  • Timeline view
  • Easy CI/CD integration

Compared to standard TestNG reports, Allure makes debugging faster and reporting more professional.


Prerequisites

Before starting, ensure you have:

  • Java 17 or later
  • Maven installed
  • Playwright project
  • TestNG framework
  • Browser binaries installed

Step 1: Add Maven Dependencies

Add the following dependencies to your pom.xml.

<dependencies>

    <dependency>
        <groupId>io.qameta.allure</groupId>
        <artifactId>allure-testng</artifactId>
        <version>2.30.0</version>
    </dependency>

    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.55.0</version>
    </dependency>

</dependencies>

Refresh your Maven project after saving the file.


Step 2: Configure Maven Surefire Plugin

Add the Surefire plugin to enable TestNG execution.

<build>

<plugins>

<plugin>

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

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

<version>3.5.3</version>

</plugin>

</plugins>

</build>

Step 3: Execute the Tests

Run your TestNG suite.

mvn clean test

During execution, Allure stores raw result files inside:

allure-results/

Each test generates JSON files containing execution details.


Step 4: Generate the Report

Once execution is complete, generate the HTML report.

allure serve allure-results

This command:

  • Builds the report
  • Starts a local server
  • Opens the report automatically in your browser

Understanding the Report Dashboard

The Allure dashboard provides valuable insights.

You'll find:

  • Total tests
  • Passed tests
  • Failed tests
  • Skipped tests
  • Duration
  • Success rate

This overview helps teams quickly assess test health.


Test Details

Clicking a test reveals:

  • Execution steps
  • Attachments
  • Error messages
  • Stack traces
  • Screenshots
  • Execution time

This detailed view speeds up root cause analysis.


Adding Screenshots to Allure

Capturing screenshots on failures greatly improves debugging.

Example helper method:

@Attachment(
value = "Failure Screenshot",
type = "image/png"
)

public byte[] attachScreenshot(Page page){

    return page.screenshot();

}

When called during a failed test, the screenshot is embedded directly in the report.


Attaching Text Logs

You can also include custom logs.

@Attachment(
value = "Execution Log",
type = "text/plain"
)

public String attachLog(String message){

    return message;

}

This is useful for recording API responses, SQL queries, or business events.


Attaching Videos

If Playwright records execution videos, attach them to the report.

@Attachment(
value = "Execution Video",
type = "video/webm"
)

public byte[] attachVideo(Path path)
throws IOException{

    return Files.readAllBytes(path);

}

Videos are invaluable when debugging intermittent failures.


Adding Test Descriptions

Allure supports annotations that make reports more readable.

@Description("Verify successful login using valid credentials")

@Test

public void loginTest(){

}

Descriptions appear directly in the report.


Categorizing Tests

Use features and stories to organize tests.

@Feature("Authentication")

@Story("Login")

@Test

public void loginTest(){

}

Reports become easier to navigate, especially in large projects.


Organizing the Project

Recommended folder structure:

project

├── allure-results

├── allure-report

├── screenshots

├── videos

├── src

├── pom.xml

└── testng.xml

Keeping artifacts separate improves project organization.


Best Practices

Capture Screenshots Only on Failure

Avoid capturing screenshots for every successful test to reduce storage usage.


Add Meaningful Descriptions

Use annotations to explain the purpose of each test.


Attach Logs for Failed Scenarios

Include:

  • API responses
  • Request payloads
  • Browser console logs
  • Custom debug messages

These details make troubleshooting much easier.


Store Environment Information

Create an environment.properties file containing details such as:

  • Browser
  • Operating system
  • Java version
  • Playwright version
  • Test environment

This information appears in the report and helps reproduce issues.


Archive Reports in CI/CD

When running tests in Jenkins, GitHub Actions, or Azure DevOps, archive the generated Allure reports as build artifacts. This allows team members to review historical execution results.


Common Interview Questions

Why is Allure preferred over the default TestNG report?

Because it provides interactive reports with screenshots, attachments, execution history, and a richer user experience.


How do you generate an Allure report?

Execute the tests and then run:

allure serve allure-results

Can Allure attach screenshots automatically?

Yes. By using the @Attachment annotation and capturing screenshots during test failures.


What types of files can be attached to Allure reports?

  • Screenshots
  • Videos
  • Text logs
  • JSON responses
  • XML files
  • PDFs
  • Any file that helps explain the test outcome

Conclusion

A good reporting solution is essential for every automation framework.

Allure Reports transform raw test execution data into an interactive, easy-to-understand dashboard that helps testers, developers, and managers quickly identify issues.

In this guide, you learned how to:

  • Integrate Allure with Playwright
  • Configure Maven
  • Generate reports
  • Attach screenshots, videos, and logs
  • Organize test results
  • Follow enterprise reporting best practices

By combining Playwright, TestNG, and Allure Reports, you can build a professional automation framework that is scalable, maintainable, and ready for enterprise projects.

Wednesday, July 8, 2026

Playwright TestNG Framework Setup Using Java (Step-by-Step Guide)

As automation projects grow, writing standalone Playwright scripts becomes difficult to maintain. Enterprise teams use testing frameworks like TestNG to organize test execution, manage test suites, perform assertions, generate reports, and execute tests in parallel.

In this guide, we'll build a Playwright TestNG framework from scratch using Java and follow industry best practices.


Why Use TestNG with Playwright?

TestNG offers several features that complement Playwright:

  • Test annotations (@Test, @BeforeMethod, @AfterMethod)
  • Test grouping
  • Parallel execution
  • Parameterized tests
  • Test dependencies
  • HTML reports
  • Easy integration with CI/CD tools

Combining Playwright with TestNG results in a scalable and maintainable automation framework.


Prerequisites

Before starting, ensure you have:

  • Java 17 or later
  • Maven installed
  • IntelliJ IDEA or Eclipse
  • Basic knowledge of Playwright
  • Browser binaries installed

Step 1: Create a Maven Project

Create a new Maven project in your IDE.

Suggested structure:

playwright-testng-framework
│
├── src
│   ├── main
│   │    └── java
│   │         ├── pages
│   │         ├── utils
│   │         └── base
│   │
│   └── test
│        └── java
│             └── tests
│
├── testng.xml
├── pom.xml
└── README.md

Step 2: Add Dependencies

Add the required dependencies to your pom.xml.

<dependencies>

    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.55.0</version>
    </dependency>

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.11.0</version>
        <scope>test</scope>
    </dependency>

</dependencies>

Refresh the Maven project after saving the file.


Step 3: Create the BaseTest Class

The BaseTest class is responsible for browser setup and cleanup.

public class BaseTest {

    protected Playwright playwright;
    protected Browser browser;
    protected BrowserContext context;
    protected Page page;

    @BeforeMethod
    public void setup() {

        playwright = Playwright.create();

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

        context = browser.newContext();

        page = context.newPage();
    }

    @AfterMethod
    public void tearDown() {

        context.close();
        browser.close();
        playwright.close();
    }
}

This ensures every test starts with a fresh browser session.


Step 4: Create a Page Object

Example LoginPage.java.

public class LoginPage {

    private final Page page;

    public LoginPage(Page page) {
        this.page = page;
    }

    public void login(String username, String password) {

        page.fill("#username", username);

        page.fill("#password", password);

        page.click("#loginButton");
    }
}

Keeping page interactions separate improves maintainability.


Step 5: Create Your First Test

Create a TestNG test class.

public class LoginTest extends BaseTest {

    @Test

    public void verifySuccessfulLogin() {

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

        LoginPage loginPage =
                new LoginPage(page);

        loginPage.login(
                "admin",
                "password123");

        assertThat(page)
                .hasTitle("Dashboard");
    }
}

Notice how the test focuses only on business logic while setup is handled by BaseTest.


Step 6: Create testng.xml

TestNG uses an XML file to define test suites.

<!DOCTYPE suite SYSTEM
"https://testng.org/testng-1.0.dtd">

<suite name="Playwright Suite">

    <test name="Smoke Tests">

        <classes>

            <class name="tests.LoginTest"/>

        </classes>

    </test>

</suite>

You can execute all tests by running this suite file.


Step 7: Execute Tests

You can run tests in several ways:

  • Directly from IntelliJ IDEA
  • Using Eclipse
  • From Maven
  • Through Jenkins or another CI/CD pipeline

Example Maven command:

mvn test

Parallel Execution

TestNG supports parallel execution through testng.xml.

Example:

<suite name="Playwright Suite"
       parallel="methods"
       thread-count="4">

</suite>

This executes four test methods simultaneously, reducing execution time.


Adding Groups

TestNG groups help organize test cases.

Example:

@Test(groups = {"Smoke"})
public void loginTest() {

}

You can create groups such as:

  • Smoke
  • Regression
  • Sanity
  • API
  • UI

Generating Reports

After execution, TestNG automatically creates reports inside the test-output folder.

Common reports include:

  • HTML report
  • Failed test report
  • Execution summary

These reports provide quick insight into test results.


Recommended Framework Structure

As your project grows, consider organizing it like this:

src
├── main
│   ├── base
│   ├── pages
│   ├── utils
│   ├── constants
│   └── listeners
│
├── test
│   ├── tests
│   ├── testdata
│   └── resources
│
├── reports
├── screenshots
├── videos
└── testng.xml

This structure is easy to maintain and scales well for enterprise projects.


Best Practices

Keep Test Logic Separate

Business actions belong in page classes, not in test methods.


Reuse Browser Initialization

Initialize Playwright once in the base class instead of repeating code.


Use Assertions Wisely

Verify business outcomes rather than implementation details.

Examples:

  • User logged in successfully
  • Order created
  • Invoice downloaded

Capture Screenshots on Failure

Integrate screenshot capture inside the @AfterMethod hook for failed tests.


Store Test Data Separately

Avoid hardcoding values.

Instead, use:

  • JSON
  • Excel
  • CSV
  • Properties files

Common Interview Questions

Why combine Playwright with TestNG?

TestNG provides test lifecycle management, reporting, grouping, parameterization, and parallel execution, making Playwright projects easier to manage.


What is the purpose of @BeforeMethod?

It runs before every test method and is commonly used to initialize the browser and create a new page.


What is the role of BaseTest?

BaseTest centralizes browser setup and cleanup, reducing code duplication across test classes.


Can Playwright tests run in parallel with TestNG?

Yes. By configuring parallel and thread-count in testng.xml, multiple tests can run simultaneously.


Conclusion

Using Playwright with TestNG is an excellent choice for building robust and maintainable Java automation frameworks.

In this tutorial, you learned how to:

  • Create a Maven project
  • Add Playwright and TestNG dependencies
  • Build a reusable BaseTest
  • Implement the Page Object Model
  • Configure testng.xml
  • Execute tests
  • Enable parallel execution
  • Apply framework best practices

With this foundation, you're ready to build enterprise-grade automation frameworks that are scalable, reusable, and easy to integrate with CI/CD pipelines.

Tuesday, July 7, 2026

How to Perform API Testing in Playwright Using Java (Complete Guide with Examples)

Modern applications rely heavily on APIs to exchange data between frontend and backend systems. While Playwright is widely known for browser automation, it also provides powerful built-in support for API testing.

This means you can automate both UI tests and REST API tests using the same framework, reducing the need for separate tools in many automation projects.

In this tutorial, you'll learn how to perform API testing in Playwright using Java with practical examples.


Why Use Playwright for API Testing?

Playwright provides a built-in HTTP client that supports:

  • GET requests
  • POST requests
  • PUT requests
  • PATCH requests
  • DELETE requests
  • Authentication
  • Custom headers
  • Query parameters
  • Response validation

Using one framework for both UI and API testing simplifies project maintenance and reduces dependencies.


Creating an API Request Context

Playwright uses an APIRequestContext to send HTTP requests.

Example:

Playwright playwright = Playwright.create();

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

The request context acts as the client for all API operations.


Sending a GET Request

Let's retrieve a list of users.

APIResponse response =
    request.get("https://reqres.in/api/users?page=2");

You can verify the response status:

System.out.println(response.status());

Expected output:

200

Reading the Response Body

To print the response content:

String body = response.text();

System.out.println(body);

This returns the JSON response as a string.


Sending a POST Request

POST requests are commonly used to create resources.

Example:

String json = """
{
  "name":"John",
  "job":"QA Engineer"
}
""";

APIResponse response =
    request.post(
        "https://reqres.in/api/users",
        RequestOptions.create()
            .setData(json)
    );

Expected status:

201 Created

Sending a PUT Request

PUT requests update existing resources.

String updateJson = """
{
  "name":"John",
  "job":"Senior QA Engineer"
}
""";

APIResponse response =
    request.put(
        "https://reqres.in/api/users/2",
        RequestOptions.create()
            .setData(updateJson)
    );

Sending a DELETE Request

Deleting resources is equally simple.

APIResponse response =
    request.delete(
        "https://reqres.in/api/users/2"
    );

Expected response:

204 No Content

Adding Custom Headers

Many APIs require custom headers.

Example:

APIResponse response =
    request.get(
        "https://example.com/api/users",
        RequestOptions.create()
            .setHeader(
                "Authorization",
                "Bearer YOUR_TOKEN"
            )
            .setHeader(
                "Content-Type",
                "application/json"
            )
    );

Sending Query Parameters

Suppose the API accepts pagination.

APIResponse response =
    request.get(
        "https://reqres.in/api/users?page=2"
    );

Alternatively, build URLs dynamically for different test scenarios.


Validating the Response

A good API test should verify more than the status code.

Example:

assert response.status() == 200;

assert response.text().contains("Michael");

You can validate:

  • Status code
  • Response body
  • Headers
  • Response time
  • Business data

Authentication

Many enterprise APIs use Bearer tokens.

Example:

APIRequestContext request =
    playwright.request().newContext(
        new APIRequest.NewContextOptions()
            .setExtraHTTPHeaders(
                Map.of(
                    "Authorization",
                    "Bearer YOUR_ACCESS_TOKEN"
                )
            )
    );

This automatically sends the token with every request.


Complete Example

Playwright playwright = Playwright.create();

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

APIResponse response =
        request.get(
            "https://reqres.in/api/users?page=2"
        );

System.out.println(
        response.status()
);

System.out.println(
        response.text()
);

request.dispose();
playwright.close();

Best Practices

Reuse the API Request Context

Create one request context and reuse it throughout your test suite instead of creating a new one for every request.


Keep Test Data Separate

Store request payloads in JSON files instead of hardcoding them inside test classes.

Example:

testdata/
    createUser.json
    updateUser.json

Validate Business Responses

Don't verify only the status code.

Also validate:

  • Response fields
  • Error messages
  • IDs
  • Dates
  • Business rules

Use Environment Variables

Store:

  • Base URL
  • Tokens
  • Credentials

inside configuration files rather than directly in code.


Common Interview Questions

Can Playwright perform API testing?

Yes.

Playwright includes a built-in HTTP client through APIRequestContext.


Which HTTP methods does Playwright support?

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

Why use Playwright for API testing?

Because it allows teams to automate both UI and API tests using the same framework, improving consistency and reducing maintenance.


How do you authenticate API requests?

Use request headers with an Authorization token or configure default headers when creating the request context.


Conclusion

Playwright is much more than a browser automation framework. Its built-in API testing capabilities make it a powerful choice for modern automation engineers.

In this tutorial, you learned how to:

  • Create an API request context
  • Send GET, POST, PUT, and DELETE requests
  • Validate responses
  • Add authentication
  • Use headers and query parameters
  • Follow best practices for scalable API automation

By combining UI and API testing within the same Playwright project, you can build efficient, maintainable, and enterprise-ready automation frameworks.