Showing posts with label POJO Class in Playwright. Show all posts
Showing posts with label POJO Class in Playwright. Show all posts

Test API using POJO Class in Playwright




1. What is a POJO Class?

  • POJO stands for Plain Old Java Object.
  • It is a simple Java class that does not extend or implement any special framework classes.
  • It is mainly used to define structured data in Java with fields, constructors, getters, and setters.
  • In the context of APIs, POJOs are used to map request and response payloads (usually JSON or XML) into Java objects, making it easier to handle data.
  • Playwright Java supports HTTP requests using the APIRequest module. You can serialize a POJO (Plain Old Java Object) to JSON and send it in the POST request body.

2. Why Use POJO in API Testing?
  • Readable & Maintainable → Instead of writing raw JSON strings, you can work with objects.
  • Reusability → The same POJO class can be used across multiple tests for request/response validation.
  • Serialization/Deserialization → Libraries like Jackson or Gson can automatically convert POJOs to JSON (for requests) and JSON back to POJOs (for responses).
  • Strong Typing → You get compile-time type safety when accessing response fields.


3. How to Test an API with POJO in Playwright Java

Although Playwright is primarily for browser automation, it provides API testing support through its APIRequestContext. Here’s how POJOs fit in:

(1) Define POJO Class

  • Create a POJO representing the request body structure (for POST/PUT).
  • Create another POJO representing the response body structure (for parsing).

(2) Serialize Request POJO to JSON

  • Use Jackson or Gson to convert the Java object (POJO) into JSON format.
  • Pass this JSON as the request body when making API calls with Playwright’s API request methods.

(3) Send API Request with Playwright

  • Use Playwright’s APIRequestContext to send GET, POST, PUT, or DELETE requests.
  • Attach headers, authentication, and the serialized JSON request if needed.

(4) De serialize Response into POJO

  • Playwright will return the response body as JSON.
  • Convert (de serialize) that JSON into a POJO class using Jackson or Gson.

(5) Assertions Using POJO

  • Instead of manually parsing JSON, directly access response fields from the POJO.
  • Example: check if responsePojo.getStatus() equals "success".

4. Advantages of Testing API with POJOs in Playwright Java
  • Cleaner test code → Work with objects, not raw JSON strings.
  • Reusable Models → Same POJO can be used across multiple test cases.
  • Consistency → Ensures request and response structures are strongly validated.
  • Scalability → Easier to expand test coverage as API complexity grows.








Steps

  • Create POJO class to represent your request payload.
  • Initialize Playwright and APIRequestContext.
  • Send POST request using .post() with the serialized POJO.
  • Validate the response.


Example:

Suppose you're testing an API endpoint:


POST https://reqres.in/api/users
Payload: { "name": "Himanshu", "job": "QA Engineer" }


















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>



1. Create POJO Class

Below is the POJO class consists of two attributes name and job and their getter and setter methods.

public class User {
    private String name;
    private String job;

    public User(String name, String job) {
        this.name = name;
        this.job = job;
    }

    // Getters and setters (optional)
    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; }
}



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!");
            }
        }
    }
}



Code explanation:

(a) Create Playwright Object and APIRequestContext object
(b) Create Pojo class object
(c) Convert POJO to JSON
(d)  Send POST request
(e) Validate the resposne



Expected Output

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

Above is the output of API with status code 201, as this is POST API and response body in the JSON format.


Important Points:

  • Gson is used to serialize the POJO into JSON.
  • RequestOptions.create().setData(jsonBody) sets the request body.
  • This approach is ideal when working with complex request bodies in APIs.


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