Showing posts with label Playwright API Testing. Show all posts
Showing posts with label Playwright API Testing. 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

How to Test Lombok API by Playwright


















What Is Lombok API? Complete Guide to Testing Lombok-Based APIs Using Playwright Java

Modern Java development often involves writing large amounts of repetitive code such as getters, setters, constructors, toString(), equals(), and hashCode() methods. This repetitive code, also known as boilerplate code, makes classes lengthy and harder to maintain. That is where Project Lombok becomes extremely useful.

In this detailed guide, you will learn:

  • What a Lombok API is

  • How Project Lombok works in Java

  • Why testing Lombok-based APIs is important

  • How to test Lombok-backed REST APIs using Playwright Java

  • A complete working example with code explanation

  • Best practices for API testing

This article is fully SEO-optimized, beginner-friendly, and written in a natural human tone to help developers understand Lombok API testing in depth.


1. What Is a Lombok API?

Before understanding a Lombok API, let’s first understand what Project Lombok is.

What Is Project Lombok?

Project Lombok is a popular Java library that reduces boilerplate code using annotations. Instead of manually writing repetitive methods, Lombok automatically generates them at compile time.

Common Lombok Annotations

Some of the most commonly used Lombok annotations include:

  • @Getter

  • @Setter

  • @Data

  • @Builder

  • @NoArgsConstructor

  • @AllArgsConstructor

  • @ToString

  • @EqualsAndHashCode

For example:

import lombok.Data; @Data public class User { private int id; private String name; private String email; }

With just @Data, Lombok automatically generates:

  • Getters and setters

  • toString()

  • equals()

  • hashCode()

  • Required constructors

This significantly improves code readability and maintainability.


2. What Do We Mean by “Lombok API”?

When developers refer to a Lombok API, they usually mean:

A REST API whose backend models (DTOs or entities) use Lombok annotations.

For example, consider a Spring Boot backend:

@Data @Builder public class UserDTO { private Long id; private String name; private String email; }

If this DTO is used in a REST controller, then the API is indirectly powered by Lombok.

Important point:

👉 Lombok runs at compile time and generates bytecode.
👉 From a testing perspective, the API behaves like any normal REST API.
👉 The test automation tool does not “see” Lombok directly.

However, we must still test the behavior that depends on Lombok-generated methods.


3. Why Testing Lombok-Based APIs Is Important

Although Lombok reduces boilerplate, improper usage can cause unexpected issues.

Key Reasons to Test Lombok APIs

1. Validate Getter and Setter Methods

Lombok generates these methods automatically. But if annotations are misconfigured, fields may not behave correctly.

2. Validate equals() and hashCode()

If @EqualsAndHashCode or @Data is used incorrectly:

  • Objects may behave incorrectly in collections like HashSet

  • Duplicate detection may fail

  • Map keys may not work properly

3. Validate toString() Output

For logging and debugging, a meaningful toString() is critical.

4. Validate @Builder Pattern

If @Builder is used:

  • Ensure all required fields are set

  • Ensure object construction works as expected

  • Validate JSON serialization matches API contract

5. Validate Serialization & Deserialization

Lombok-generated models are often serialized into JSON. If misconfigured:

  • JSON fields may be missing

  • Naming conventions may mismatch

  • API contract may break


4. How to Test Lombok APIs Using Playwright Java

Now let’s discuss how to test a Lombok-powered REST API using Playwright Java.

Although Playwright is primarily known for UI automation, it also provides strong API testing capabilities using APIRequestContext.

However, in many enterprise projects, developers also use:

  • Java HttpClient

  • RestAssured

  • OkHttp

In this guide, we will use:

  • Playwright Java

  • Java HttpClient


5. Steps to Test a Lombok-Based API

Here’s the structured approach:

Step 1: Set Up Playwright Java Project

Add Maven dependency:

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

Make sure Java 11+ is installed.


Step 2: Understand the Example API

Assume we have a backend API built using Lombok models.

API Endpoint

POST http://localhost:8080/api/users

Request Body

{ "name": "John Doe", "email": "john@example.com" }

Response

{ "id": 1, "name": "John Doe", "email": "john@example.com" }

The backend uses Lombok annotations like @Data and @Builder.


6. Complete Java Code to Test Lombok API

Here is a working example using Playwright Java + HttpClient:

import com.microsoft.playwright.*; import java.net.URI; import java.net.http.*; import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpRequest.BodyPublishers; public class LombokApiTest { public static void main(String[] args) throws Exception { // Start Playwright try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(true)); BrowserContext context = browser.newContext(); Page page = context.newPage(); // Create HttpClient HttpClient client = HttpClient.newHttpClient(); // JSON Request Body String jsonBody = """ { "name": "John Doe", "email": "john@example.com" } """; // Create HTTP Request HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8080/api/users")) .header("Content-Type", "application/json") .POST(BodyPublishers.ofString(jsonBody)) .build(); // Send Request HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); // Print Response System.out.println("Status Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); // Validate Status if (response.statusCode() == 200 || response.statusCode() == 201) { System.out.println("API Test Passed"); } else { System.out.println("API Test Failed"); } browser.close(); } } }


7. Code Explanation (Step-by-Step)

(a) Create Playwright Instance

Playwright playwright = Playwright.create();

This initializes Playwright.


(b) Launch Browser (Optional)

Browser browser = playwright.chromium().launch(...);

We use this if we want to verify the UI after API execution.


(c) Create Java HttpClient

HttpClient client = HttpClient.newHttpClient();

This is used to send HTTP requests.


(d) Define JSON Request Body

We prepare the payload that will be sent to the Lombok-backed API.


(e) Build and Send HTTP Request

HttpRequest request = HttpRequest.newBuilder()...

Then:

client.send(request, BodyHandlers.ofString());


(f) Validate Response

We check:

  • Status Code (200 or 201)

  • Response Body content


8. How Lombok Affects API Testing

Even though Lombok is not directly visible in API testing, its generated methods impact:

1. Object Creation

If backend uses:

@Builder public class UserDTO { ... }

We must validate that:

  • Required fields are not null

  • Builder sets values correctly

  • API returns correct JSON


2. Equality Checks

If @EqualsAndHashCode is used:

  • Duplicate users should not exist

  • API must behave correctly in list operations


3. JSON Serialization

If Lombok fields are private and getters are generated:

  • JSON must include expected keys

  • Field names must match API contract


9. Advanced Validation in API Testing

Instead of just checking status codes, you should validate:

Validate JSON Fields

Example (pseudo validation):

  • Ensure response contains "name": "John Doe"

  • Ensure "id" is not null

  • Ensure email format is correct


Validate Data Consistency

After POST:

  1. Call GET /api/users/{id}

  2. Ensure returned data matches inserted data


Negative Testing

Test error scenarios:

  • Missing email

  • Invalid format

  • Duplicate entries

Expected responses:

  • 400 Bad Request

  • 409 Conflict

  • 422 Unprocessable Entity


10. Best Practices for Testing Lombok APIs

1. Don’t Assume Lombok Always Works

Even though Lombok generates code, test behavior thoroughly.


2. Always Validate API Contract

Use schema validation if possible.


3. Test Builder Patterns Carefully

Ensure:

  • Required fields are enforced

  • Optional fields behave correctly


4. Combine API and UI Testing

With Playwright, you can:

  • Create user via API

  • Validate user appears in UI

This ensures end-to-end validation.


5. Use Assertions Framework

For production projects, use:

  • JUnit

  • TestNG

  • AssertJ

Instead of simple if statements.


11. Tools Used in This Setup

Java HttpClient

Used for sending REST requests.

Playwright Java

Used for:

  • UI automation

  • API testing

  • End-to-end testing

Lombok (Backend Only)

Used to:

  • Reduce boilerplate

  • Generate model methods

  • Improve maintainability


12. Common Mistakes When Testing Lombok APIs

  1. Ignoring equals/hashCode behavior

  2. Not validating builder-generated objects

  3. Skipping negative testing

  4. Only checking status code

  5. Not verifying serialization output


13. Final Thoughts

Testing a Lombok-based API is fundamentally the same as testing any REST API. However, because Lombok generates methods at compile time, it is essential to validate that:

  • Generated getters/setters work correctly

  • Builder pattern constructs valid objects

  • JSON serialization matches expected API contract

  • equals() and hashCode() behave properly

Using Playwright Java along with Java HttpClient provides a powerful and flexible solution for testing REST APIs.

By following structured API testing practices, validating both positive and negative scenarios, and combining backend and frontend validation, you can build reliable, maintainable, and production-ready automation frameworks.


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. Test API by POJO Class in Playwright