top of page
Search

How to create POJO classes for Api Automation with RestAssured

  • Writer: Dev Raj Sinha
    Dev Raj Sinha
  • Jun 15, 2023
  • 2 min read

The POJO class is an object class that encapsulates the Business logic. It has then entities for a particular Api and setter and getter for that payload as an business logic. There are various ways to create POJO. I'll discuss couple of them here, the most longest and the most faster way.


In addition I'll tell you how to Serialize and deserialize the pojo Objects to and from json when doing the api call from RestAssured.


1. The longest way -


Lets assume you have an POST API - /travelPackage to create a new package in a travel website


public class TravelPackage {
    public String place;
    public String price;
    
    // A function to set place value
    public void setPlace(String place) {
        this.place = place;
    }
    
    // A function to set price value
    public void setPrice(String price) {
        this.price = price;
    }
    
    //A function to get place value
    public String getPlace() {
        return this.place;
    }
    
    //A function to get price value
    public String getPrice() {
        return this.price;
    }
}

2. The shortest way - It is by using the Lombok plugin to create the setter and getter functions


import lombok.Setter;
import lombok.Getter;
    
@Setter @Getter    
public class TravelPackage {
    public String place;
    public String price;
}

I prefer this one due to very shorthand in writing the POJO class here. The annotations are really helpful and this is automatically create your setter and getter functions for all the variables that are present in that particular class.


Below is the code to how to actually make the class objects and call the api from RestAssured.


public class TestTravelPackage {
    TravelPackage travelpackage1 = new TravelPackage();
    travelpackage1.setPlace("Australia");
    travelpackage1.setPrice("Price");
    
    // Object Mapper is from the Jackson package used to serialize the class object to Json
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    // Her we converting POJO object to json
    String jsonLoad = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(travelpackage1);    
    
    // Calling the Api for response
    RequestSpecification req = RestAssured.given();
     String count = req.log().all()
                    .body(jsonLoad)
                    .when()
                    .post("http://www.travel.com" + /travelPackage)
                    .then()
                    .assertThat()
                    .statusCode(200);
     




 
 
 

Recent Posts

See All

Commentaires


Never Miss a Post. Subscribe Now!

Find new exciting ways to dominate the IT Automation industry

Thanks for submitting!

bottom of page