Skip to main content

Serialization in Rest Assured

Serialization is the process of converting the java objects into a stream of data. So why do we need to convert an object into a stream of data?

Let me give a simple example:

  • So say you wanna send a java object to the blog data.
  • You can convert this java object into a byte stream and then transfer it over the internet using the JSON stream.
  • So after whenever you receive data you can basically deserialize and use it back to your convenience.
  • It's like send something over and fetching it like a boomerang but here the boomerang has some data.
  • So that makes serialization and deserialization platforms independent which means you can serialize and deserialize from one platform to a different platform.

So how do we do it?

  • In this article, we will see just how serialization works with an example.
  • We are using a fake rest API service to post some JSON objects.
  • https://gorest.co.in/
  • The first thing you have to do after reaching the site generates your unique token to POST, GET your request.
  • https://gorest.co.in/access-token - use this to generate a unique bearer authentication token.

So the site has the JSON body as below :

{
    "id": 1010,
    "name": "trinity",
    "email": "mana@matrix.com",
    "gender": "Female",
    "status": "active"
}
  • Use this body and pass your data.
  • So after posting normally say I post some data in postman and when I GET it with https://gorest.co.in/public/v1/users/{id}

It sends a response as:

{
    "meta": null,
    "data": {
        "id": 1319,
        "name": "trinity",
        "email": "mana@matrix.com",
        "gender": "female",
        "status": "active"
    }
}
  • Now, this is very important for this method we have to write the POJO class based on this JSON body.

Enough talk we will jump into the coding example step by step.

STEP 1 (POJO(Plain Old Java Object) Creation)

{
    "meta": null,
    "data": {
        "id": 1319,
        "name": "trinity",
        "email": "mana@matrix.com",
        "gender": "female",
        "status": "active"
    }
}

From this JSON we have meta, data, and within data the main JSON payload.

Let's first create some getters and setters for main and data first.

import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;

public class firstPojo 
{
    private String meta;
    private List<dataPojo> data;

    public String getMeta()
    {
        return meta;
    }

    public void setMeta(String meta)
    {
        this.meta = meta;
    }

    public List<dataPojo> getData()
    {
        return data;
    }

    @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
    public void setData(List<dataPojo> data)
    {
        this.data = data;
    }

    @Override
    public String toString()
    {
        return "firstPojo [meta=" + meta + ", data=" + data + "]";
    }
}
  • Here as data consists of the payload we are passing the datapojo which is the second POJO for the payload to here in the firstpojo class as we need a list of the payload.
  • We are setting getter as list<dataPojo> which returns data and also we are setting toString as well.

Let's see what the dataPojo class looks like.

package serialization;

public class dataPojo
{
    private int id;
    private String name;
    private String email;

    private String gender;
    private String status;

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getEmail()
    {
        return email;
    }
    
    public void setEmail(String email)
    {
        this.email = email;
    }

    public String getGender()
    {
        return gender;
    }

    public void setGender(String gender)
    {
        this.gender = gender;
    }

    public String getStatus()
    {
        return status;
    }

    public void setStatus(String status)
    {
        this.status = status;
    }

    @Override
    public String toString() 
    {
        return "dataPojo [id=" + id + ", name=" + name + ", email=" + email + ", gender=" + gender + ", status=" + status
            + "]";
    }
}
  • So you get the idea right we are passing this class into the setter of firstPojo setData as a list as it returns the list of the JSON payload.
  • So creating the POJO is complete.

STEP 2 (Serialization Class)

So before we dive into the main serialization part here are the POM dependencies I'm using for maven.

  • So there's that we can move on to our rest assured serialization integration part.

 Create a class for serialization.

import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

public class serialDeserialTest 
{
    private static final ObjectMapper MAPPER = new ObjectMapper();
    
    @Test
    public void serTest() throws JsonProcessingException
    {
        dataPojo dp = new dataPojo();
        
        dp.setId(1010);
        dp.setName("trinity");
        dp.setEmail("mana@matrix.com");
        dp.setGender("Female");
        dp.setStatus("active");
    
        String url = "https://gorest.co.in/public/v1/users/";
        String json = MAPPER.writeValueAsString(dp);
    
        Response response = RestAssured.given().header("Authorization","Bearer 22165c6cdaa5a062950d45595824ad289743ef9eb6d8ef5d156691aaf876f70").contentType("application/json").log().all().body(dp).when().post(url).andReturn();
    
        int statusCode = response.getStatusCode();
        assertEquals(201, statusCode);
    
        Response response2 = RestAssured.get("https://gorest.co.in/public/v1/users?email=mana@matrix.com");
        JsonPath js = new JsonPath(response2.asString());                                                     
        String id = js.getString("data[0].id");
    
        System.out.println("****************************");
        System.out.println(id);
        System.out.println("****************************");
       
        Response response3 = RestAssured.get("https://gorest.co.in/public/v1/users/"+id);
        System.out.println(response3.asString());
    }
}
  • I'm using TestNG for this u can even run this in the main method too.
  • So I'm declaring a mapper class that will send/writes the data in JSON in simple term it maps the data you are setting in the DP object into JSON string payload.
  • I'm creating a new object for the datapojo POJO class we created and setting the payload data to send.
  • Then we are sending POST via rest assured response.
  • NOTE: In the header, place paste your unique token here I have used mine.
  • So in goapi, any id you set is useless as it generates a unique id after you POST.
  • So to get that id I have used the GET request using the URL and filtering out the email I have set.
  • Converted to JSON string and passed to the response3 I have created and printed to check whether the POST is done successfully.

Output:

[RemoteTestNG] detected TestNG version 6.14.3
Request method:    POST
Request URI:    https://gorest.co.in/public/v1/users/
Proxy:            <none>
Request params:    <none>
Query params:    <none>
Form params:    <none>
Path params:    <none>
Headers:        Authorization=Bearer 22165c6cdaa5a062950d4559b5824ad289743ef9eb6d8ef5d156691aaf876f70
                Accept=*/*
                Content-Type=application/json; charset=UTF-8
Cookies:        <none>
Multiparts:        <none>
Body:
{
    "id": 1010,
    "name": "trinity",
    "email": "aam@matrix.com",
    "gender": "Female",
    "status": "active"
}
****************************
1332
****************************
{"meta":null,"data":{"id":1332,"name":"trinity","email":"aam@matrix.com","gender":"female","status":"active"}}

PASSED: serTest

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Verdict :

  • Now as you can see the java object from the POJO has been successfully serialized and sent to the gopi rest site using the POST method.
  • We will see how to deserialize this data and get the list of the payload in another article.
Submitted by arilio666 on September 28, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.