Showing posts with label Playwright. Show all posts
Showing posts with label Playwright. Show all posts

Test API using POJO Class in Playwright


















What Is a POJO Class? Complete Guide to Testing APIs with POJO in Playwright Java

When working with REST APIs in Java automation frameworks, one of the most important concepts you’ll encounter is the POJO class. If you are performing API testing using Playwright Java, understanding POJOs can significantly improve your test structure, readability, and maintainability.

In this detailed, SEO-optimized guide, you will learn:

  • What a POJO class is

  • Why POJOs are important in API testing

  • How to use POJO classes in Playwright Java

  • How serialization and deserialization work

  • Step-by-step example with complete code

  • Best practices for scalable API automation

This article is written in a clear, human-friendly style to help both beginners and experienced automation engineers.


1. What Is a POJO Class?

POJO stands for Plain Old Java Object.

A POJO is a simple Java class that:

  • Does not extend special framework classes

  • Does not implement framework-specific interfaces

  • Contains fields (variables)

  • Contains constructors

  • Contains getter and setter methods

In simple terms, a POJO is just a normal Java class used to represent data.

Example of a Simple POJO

public class User { private String name; private String job; public User(String name, String job) { this.name = name; this.job = job; } public String getName() { return name; } public String getJob() { return job; } public void setName(String name) { this.name = name; } public void setJob(String job) { this.job = job; } }

This class represents structured data.


2. Role of POJO in API Testing

In API automation testing, especially REST API testing, data is usually transferred in:

  • JSON format

  • XML format

When testing APIs in Java, we often need to:

  • Send request payloads

  • Read response payloads

  • Validate response fields

Instead of writing raw JSON strings inside test code, we use POJOs to represent structured data.

For example:

{ "name": "Himanshu", "job": "QA Engineer" }

Instead of writing the JSON manually, we can create a User POJO and convert it to JSON.

This approach makes test automation:

  • Cleaner

  • More readable

  • Easier to maintain


3. Why Use POJO in API Testing?

Using POJO classes in API testing provides multiple benefits.

1. Readable and Maintainable Code

Working with Java objects is much easier than handling raw JSON strings.

Instead of:

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

You can write:

User user = new User("Himanshu", "QA Engineer");

This improves clarity.


2. Reusability

The same POJO class can be reused:

  • Across multiple test cases

  • For POST and PUT requests

  • For response validation

If the API structure changes, you only update the POJO class instead of editing JSON in multiple tests.


3. Serialization and Deserialization

Libraries like:

  • Gson

  • Jackson

Allow you to:

  • Convert POJO → JSON (Serialization)

  • Convert JSON → POJO (Deserialization)

This automatic conversion makes API testing powerful and structured.


4. Strong Typing

When you deserialize JSON into a POJO:

  • You get compile-time type checking

  • You avoid runtime JSON parsing errors

  • You can directly access fields using getters

Example:

responsePojo.getName();

Instead of manually parsing JSON.


4. Using POJO in Playwright Java for API Testing

Playwright is primarily known for browser automation, but it also provides API testing support through APIRequestContext.

When testing APIs in Playwright Java:

  1. Define POJO class

  2. Serialize POJO to JSON

  3. Send API request

  4. Deserialize response

  5. Perform assertions

Let’s understand this step-by-step.


5. Steps to Test an API with POJO in Playwright Java

Step 1: Add Maven Dependencies

<dependencies> <dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency> </dependencies>

These dependencies allow:

  • Playwright API testing

  • JSON serialization using Gson


6. Example API Scenario

We will test the following endpoint:

POST https://reqres.in/api/users

Payload

{ "name": "Himanshu", "job": "QA Engineer" }

This API is provided by ReqRes, a free REST API for testing.


7. Step 1: Create POJO Class

public class User { private String name; private String job; public User(String name, String job) { this.name = name; this.job = job; } public String getName() { return name; } public String getJob() { return job; } public void setName(String name) { this.name = name; } public void setJob(String job) { this.job = job; } }

This class represents the request structure.


8. Step 2: Main Test Code Using Playwright

import com.microsoft.playwright.*; import com.google.gson.Gson; import com.microsoft.playwright.options.*; public class PostApiTest { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { APIRequestContext request = playwright.request().newContext(); // Create POJO object User user = new User("Himanshu", "QA Engineer"); // Convert POJO to JSON Gson gson = new Gson(); String jsonBody = gson.toJson(user); // Send POST request APIResponse response = request.post("https://reqres.in/api/users", RequestOptions.create() .setHeader("Content-Type", "application/json") .setData(jsonBody) ); // Validate response System.out.println("Status: " + response.status()); System.out.println("Response Body: " + response.text()); if (response.status() == 201) { System.out.println("POST request successful!"); } else { System.out.println("POST request failed!"); } } } }


9. Code Explanation (Detailed)

(a) Create Playwright Object

Playwright playwright = Playwright.create();

Initializes Playwright environment.


(b) Create APIRequestContext

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

This acts as an HTTP client for sending API requests.


(c) Create POJO Object

User user = new User("Himanshu", "QA Engineer");

Instead of writing JSON manually, we use Java object.


(d) Serialize POJO to JSON

Gson gson = new Gson(); String jsonBody = gson.toJson(user);

Converts Java object into JSON string.


(e) Send POST Request

request.post(...)

We attach:

  • Content-Type header

  • JSON request body


(f) Validate Response

We check:

  • Status code (201 Created)

  • Response body


10. Expected Output

Status: 201 Response Body: { "name": "Himanshu", "job": "QA Engineer", "id": "734", "createdAt": "2025-07-28T10:52:45.108Z" } POST request successful!

A 201 status confirms successful resource creation.


11. Deserializing Response into POJO (Advanced)

Instead of printing raw JSON, you can create a response POJO:

public class UserResponse { private String name; private String job; private String id; private String createdAt; // getters and setters }

Then:

UserResponse responseObj = gson.fromJson(response.text(), UserResponse.class); System.out.println(responseObj.getId());

This is called deserialization.

Benefits:

  • Direct field access

  • Strong validation

  • Cleaner assertions


12. Advantages of Using POJO in Playwright API Testing

Cleaner Test Code

No messy JSON strings.


Reusable Models

Same POJO works across:

  • POST tests

  • PUT tests

  • Response validation


Strong Validation

Fields are validated at compile-time.


Easy Maintenance

If API adds a new field:

  • Just update POJO

  • No need to edit all test files


Scalable Framework

In large enterprise projects:

  • Hundreds of APIs

  • Complex nested JSON

POJOs make framework scalable and structured.


13. Best Practices for POJO-Based API Testing

1. Separate Request and Response POJOs

Avoid mixing request and response models.


2. Use Builder Pattern for Complex Payloads

For large JSON structures, consider builder pattern.


3. Use Assertions Framework

Instead of:

if (response.status() == 201)

Use:

  • JUnit

  • TestNG

  • AssertJ


4. Handle Nested JSON Properly

For nested objects:

{ "user": { "name": "Himanshu" } }

Create nested POJO classes.


5. Validate Schema When Needed

Use schema validation for contract testing.


14. Common Mistakes to Avoid

  • Writing raw JSON everywhere

  • Not deserializing response

  • Ignoring response validation

  • Mixing test logic and data models

  • Hardcoding values repeatedly


15. Final Thoughts

A POJO (Plain Old Java Object) is one of the most important building blocks in Java-based API automation.

When combined with:

  • Playwright Java

  • Gson or Jackson

  • Structured test design

It provides:

  • Clean code

  • Strong validation

  • Reusable models

  • Scalable automation frameworks

Testing APIs using POJOs ensures your automation framework is professional, maintainable, and production-ready.

If you are serious about mastering API automation with Playwright Java, learning how to properly design and use POJO classes is absolutely essential.



Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Basic Authentication in Playwright
5. Token Bsed Authentication in Playwright

Comma Selectors in Playwright

















Comma Selectors in Playwright Java – Complete Guide with Examples

When working with modern web automation frameworks, flexibility in element selection is extremely important. In Playwright Java, one powerful yet often underused feature is the comma selector. Comma selectors allow you to combine multiple CSS selectors into a single locator, making your automation scripts more efficient, readable, and maintainable.

In this comprehensive guide, you’ll learn:

  • What comma selectors are in Playwright

  • How comma selectors work in Playwright Java

  • Practical real-world use cases

  • Java code examples with explanation

  • Best practices for maintainable test automation

  • SEO-friendly automation insights for testers and developers

If you are learning Playwright automation with Java, this guide will help you write smarter locators and reduce duplication in your test scripts.


What Are Comma Selectors in Playwright?

In Playwright Java, comma selectors refer to compound CSS selectors separated by commas (,) that allow you to target multiple elements at once.

This works exactly like standard CSS selector grouping.

Basic Syntax

Locator locator = page.locator("selector1, selector2, selector3");

This means:

  • Match all elements that satisfy selector1

  • OR match all elements that satisfy selector2

  • OR match all elements that satisfy selector3

Playwright merges all matching elements into a single Locator collection.

Why Use Comma Selectors in Playwright?

Comma selectors are extremely useful in automation testing when:

  • An element may appear in different formats.

  • UI changes dynamically (mobile vs desktop).

  • Different builds show slightly different element names.

  • You want to perform bulk operations on multiple element types.

Instead of writing separate locators and conditionally handling them, you can combine them in a single line.

This improves:

  • Test readability

  • Code reusability

  • Maintenance

  • Stability of automation scripts


How Comma Selectors Work in Playwright Java

Let’s understand how Playwright evaluates comma selectors step by step.

1. Multiple Selectors in One Locator

When you write:

page.locator("a:has-text('Gmail'), a:has-text('GoogleMail')");

Playwright will:

  • Find all <a> elements containing "Gmail"

  • Find all <a> elements containing "GoogleMail"

  • Combine results into one locator


2. Merging Results

If both selectors match elements, Playwright merges them into a single collection.

You can then:

  • Click

  • Count

  • Assert visibility

  • Extract text

  • Filter using nth(), first(), or last()


3. Works Like CSS

Since Playwright supports CSS selectors, comma selectors follow standard CSS behavior.

Example:

page.locator("h1, h2, h3");

This selects all heading elements from <h1>, <h2>, and <h3>.


Website Example Used in This Guide

We will use:

https://www.google.com/

This example demonstrates how comma selectors work when selecting links like:

  • Gmail

  • Images

  • GoogleMail (if present in some variations)


Complete Java Playwright Example – Comma Selectors

Below is the full working Playwright Java code:

import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserType; import com.microsoft.playwright.Locator; import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; public class CommaSelectorsExample { public static void main(String[] args) { // this code will click Gmail or if instead of Gmail GoogleMail is present like or condition Playwright playwright = Playwright.create(); Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false)); Page p1 = browser.newPage(); p1.navigate("https://www.google.co.in"); p1.locator("a:has-text('Gmail'),a:has-text('GoogleMail') ").click(); //For two links comma separated selector code is there Page p2 = browser.newPage(); p2.navigate("https://www.google.co.in"); Locator lc = p2.locator("a:has-text('Gmail'),a:has-text('Images') "); System.out.println(lc.count()); //click on Gmail by using xpath Page p3 = browser.newPage(); p2.navigate("https://www.google.co.in"); Locator gmailLocator = p2.locator("//a[text()='Gmail'] | //a[text()='GooleMail'] "); System.out.println(gmailLocator.textContent()); gmailLocator.click(); browser.close(); playwright.close(); } }


Code Explanation in Detail

Let’s break the code into simple steps so beginners can clearly understand it.


(a) Launching the Browser

Playwright playwright = Playwright.create(); Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
  • Creates Playwright instance

  • Launches Chromium browser

  • setHeadless(false) allows you to see browser execution


(b) Navigating to the Website

p1.navigate("https://www.google.co.in");

This opens Google homepage.


(c) Using Comma Selector for OR Condition

p1.locator("a:has-text('Gmail'),a:has-text('GoogleMail') ").click();

This means:

  • If "Gmail" link exists → click it

  • If "GoogleMail" exists instead → click it

This behaves like a logical OR condition in automation.


(d) Counting Multiple Elements

Locator lc = p2.locator("a:has-text('Gmail'),a:has-text('Images') "); System.out.println(lc.count());

This counts how many elements match:

  • Gmail

  • Images

If both exist → count = 2
If only one exists → count = 1


(e) XPath Alternative Using Pipe Operator

Locator gmailLocator = p2.locator("//a[text()='Gmail'] | //a[text()='GooleMail'] ");

Here:

  • | works as OR in XPath

  • Similar concept to comma in CSS


Real-World Use Cases of Comma Selectors in Automation

Let’s explore practical automation scenarios.


1. Handling UI Variations

Sometimes in different environments:

  • Dev shows "Submit"

  • QA shows "Continue"

  • Prod shows "Proceed"

Instead of writing separate logic:

page.locator("button:has-text('Submit'), button:has-text('Continue'), button:has-text('Proceed')").click();

This makes your test environment-independent.


2. Mobile vs Desktop Testing

In responsive websites:

  • Desktop: <button>

  • Mobile: <a> styled as button

You can write:

page.locator("button#login, a#login").click();


3. Bulk Heading Validation

Locator headings = page.locator("h1, h2, h3"); System.out.println("Total headings: " + headings.count());

Useful for SEO validation testing.


4. Error Message Validation

Sometimes error messages appear as:

  • <div class="error">

  • <span class="error-text">

You can combine:

page.locator("div.error, span.error-text");


Advantages of Comma Selectors in Playwright

1. Reduces Code Duplication

No need to write multiple locators.

2. Improves Maintainability

One combined selector is easier to update.

3. Cleaner Test Logic

Avoids complex if-else blocks.

4. Flexible for Dynamic UIs

Works well with modern JavaScript-heavy applications.


Important Points to Remember

✔ Comma selectors follow CSS rules.
✔ Playwright returns a merged list of matched elements.
✔ You can filter using .first(), .last(), .nth(index).
✔ Use carefully — too many combined selectors reduce readability.


Best Practices for Using Comma Selectors

To keep your automation framework maintainable:

Use Only When Necessary

Don’t combine unrelated elements.

Keep Selectors Readable

Avoid extremely long comma-separated selectors.

Prefer Unique Identifiers

If possible, use id, data-testid, or stable attributes.

Combine with Assertions

After locating, verify visibility:

Locator element = page.locator("selector1, selector2"); if(element.count() > 0){ element.first().click(); }


CSS vs XPath – OR Conditions

Selector TypeOR Syntax
CSSselector1, selector2
XPath`//path1

Both achieve similar functionality.

In Playwright Java:

  • CSS is generally faster and cleaner.

  • XPath is useful for complex DOM traversal.


When NOT to Use Comma Selectors

Avoid using them when:

  • Elements are unrelated.

  • You need strict element control.

  • Test clarity is reduced.

Overusing comma selectors can make debugging harder.


Advanced Example – Filtering After Comma Selector

Locator locator = page.locator("button.primary, button.secondary"); locator.filter(new Locator.FilterOptions().setHasText("Submit")).click();

This selects:

  • Either primary or secondary button

  • But only if it contains "Submit"


Summary

Comma selectors in Playwright Java are a powerful way to:

  • Combine multiple element locators

  • Handle dynamic UI changes

  • Reduce duplication

  • Improve automation efficiency

They work exactly like CSS comma-separated selectors and are extremely helpful in real-world automation scenarios.

By using comma selectors wisely, you can create:

  • Stable automation frameworks

  • Clean test cases

  • Scalable test architecture

If you are preparing for automation interviews or building enterprise-level frameworks, mastering comma selectors will give you an edge.



Suggested Posts:

1. Handle IFrames in Playwright
2. Automate Login Page in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. Handle Dynamic Webtable in Playwright