top of page
shubameg48

Serialization and Deserialization in Rest Assured API Testing of LMS API Service

In Java, Serialization is a process of converting an object from its current state to a stream of bytes which can be written to a file or transported through a network or stored in a database. De-serialization is rebuilding the object from stream of bytes.

Pre-requisites:

  • Basic knowledge of making http calls with request payload using Rest Assured.

  • API service that I have used for my project here is LMS API service.

  • https://lms-program-rest-service.herokuapp.com/programs

  • The following should be installed in the system:-Java, IDE(I have used Eclipse), Maven

Relevant POM libraries-latest versions Rest Assured 4.4.0 json Schema validator 4.3.3 jackson databind 2.12.5 jackson core 2.12.5 jackson annotations 2.12.5 gson 2.8.6 TestNG 7.3

and now your project is ready to support serialization and deserialization.

Let’s take an example of a json that we intend to send as request payload for a Post operation, to the end point while making an http Post call to the LMS server.

{ “online”: true, “programDescription”: “String”, “programId”: 0, “programName”: “String” }

There are several ways to construct our request payloads.

  • We can provide the json directly into the body by providing special characters in a string

  • We can provide static json payload into a file and we can send that json file as an input by giving the path

  • Wrap up a full json payload into a method and sending the parameters dynamically into that method

  • We can create json using Hashmap

  • Creating a java object out of json — and This is what I’m going to demonstrate here!

First, We can create a POJO class(Plain Old Java Object), which has better readability and serves re-usability purpose. How do we do this?

Observe the json payload again. Do you see the format in Keys and values? For every key in the json, we will create a variable for the same, inside a class.

eg. private String programName;

Then for that particular variable, we need to create two methods which are getters and setters.

We can define the getter method as ‘get’ followed by variable name(see example). This method returns key “programName” passed through json payload. eg.

public String getProgramName() { return programName; }

We can define the setter method as ‘set’ followed by variable name. This method helps in setting the value to the variable “programName” passed thro’ json payload. public void setProgramName(String programName) { this.programName = programName; }

Similarly, let’s create variables and methods for rest of the key and value pairs from our intended json request payload. Make sure to create all the variables as private and all methods as public. This is the standard for defining POJO class.

An alternate and EASY way of creating this getters and setters methods is- First, declare all fields as private. Next highlight on the fields, press ‘Alt+shift+s’ right click and choose “Generate Getters and Setters” Rest Assured automatically creates all the methods without hassle.


package funcTesting;

public class ProgramInfo {
private String programId;
private String programName;
private String programDescription;
private String online;

public String getProgramId() {
return programId;
}
public void setProgramId(String programId) {
this.programId = programId;
}
public String getProgramName() {
return programName;
}
public void setProgramName(String programName) {
this.programName = programName;
}
public String getProgramDescription() {
return programDescription;
}
public void setProgramDescription(String programDescription) {
this.programDescription = programDescription;
}
public String getOnline() {
return online;
}
public void setOnline(String online) {
this.online = online;
}
}

Now, the POJO class is ready!

In the following Test class, we will create a Rest Assured Test to complete the serialization process by passing the above pojo class to the API.

First, We will create an object of the above pojo class as

ProgramInfo pinfo = new ProgramInfo();

Rest Assured will automatically convert the POJO class into a json object and as of now the setters will be empty { “programId”: “0”, “programName”: “ ”, “programDescription”: “ ”, “online”: “ ” }

In java, after we create the object, we can access the methods present in the class. Next, using the reference object, set the values with the help of setters methods. pinfo.setOnline(“true”); pinfo.setProgramDescription(“Intro to Sql by shu220”); pinfo.setProgramId(“0”); pinfo.setProgramName(“SQL220”);

These values are passed to the setter methods as arguments and are passed to the private variables through ‘this’ keyword (In java this keyword refers to the current class variables). Now, once the values are assigned to the variables, automatically the values are filled inside the json object as in..

{ “programId”: “0”, “programName”: “SQL220”, “programDescription”: “Intro to Sql by shu220”, “online”: “true” }

Finally, write the Rest Assured test script and pass the ‘pinfo’ object as part of request payload body to make the Post call.


package funcTesting;
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;

public class PojoTest1_lms {
@Test
public void tosetProgramDetails()
{
ProgramInfo pinfo = new ProgramInfo();
 pinfo.setOnline("true");
pinfo.setProgramDescription("Intro to Sql by shu220");  pinfo.setProgramId("0");
pinfo.setProgramName("SQL220");
RestAssured.baseURI="https://lms-program-rest-service.herokuapp.com/programs";
Response res = given().log().all().auth().basic("admin","password")
.header("Content-Type","application/json")
.body(pinfo)
.when().post().then().assertThat().statusCode(200).extract().response();
String response = res.asString();
System.out.println(response);
}
}

All these process of converting the java object(using POJO classes)into request payload is Serialization.

How good is serialization without understanding De-serialization. That follows …

Deserialization in Rest Assured is converting Responsebody back to java object with the support of pojo classes. If the response is wrapped as java object, then it is easy to parse and extract response using getters methods. yes, POJO classes are created here too. Just that the variables in this pojo class are created for the Keys of json response body.

Let’s come to our LMS API sample.

Our LMS API responsebody looks something like this- [

{ “online”: true, “programDescription”: “String”, “programId”: 0, “programName”: “String” } { “programId”: 338, “programName”: “SQL220”, “programDescription”: “Intro to Sql by shu220”, “online”: “true” }

]

Here, the endpoint ‘/Programs’ from the LMS api has similar data of multiple programs, hence the data has been designed to be stored in the array format. Now, How do we convert this simple JSON Array response that we receive from hitting our LMS API to a POJO class, so that we can extract any response out of it easily?

First, we need to create a POJO class for the Keys from the response body. But wait, don’t we already have the pojo class for this with all the fields and getters and setters methods as in- programInfo.java


package funcTesting;
public class ProgramInfo {
private String programId;
private String programName;
private String programDescription;
private String online;

public String getProgramId() {
return programId;
}
public void setProgramId(String programId) {
this.programId = programId;
}
public String getProgramName() {
return programName;
}
public void setProgramName(String programName) {
this.programName = programName;
}
public String getProgramDescription() {
return programDescription;
}
public void setProgramDescription(String programDescription) {
this.programDescription = programDescription;
}
public String getOnline() {
return online;
}
public void setOnline(String online) {
this.online = online;
}

So we will just head to creation of Deserialization test-

We need to parse response using POJO class. But the current pojo class has only one program detail.

Then how do we handle multiple responses that is wrapped under a JSON array?

When we convert the response to pojo class, we need to convert the class as an array eg. .as(programInfo[].class) and store the results in a variable of arrayclass type.

Now we can easily call the response of the last added program using indexes.


package funcTesting;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import io.restassured.RestAssured;public class PojoTest2_lms {
@Test
public void getPojoFromProgramInfoObject() throws JsonMappingException,JsonProcessingException{
//Deserialization
ProgramInfo[] allprogramdetails = RestAssured.given().auth().basic("admin", "password").log().all()
.when().get("https://lms-program-rest-service.herokuapp.com/programs").as(ProgramInfo[].class);

System.out.println("no of programs: "+ allprogramdetails.length);

System.out.println("Program Name: "+allprogramdetails[allprogramdetails.length-1].getProgramId());

System.out.println("Program Name: "+allprogramdetails[allprogramdetails.length-1].getOnline());

System.out.println("Program Name: "+allprogramdetails[allprogramdetails.length-1].getProgramName());

System.out.println("Program Description: "+allprogramdetails[allprogramdetails.length-1].getProgramDescription());
}
}

A variation — In real time, we might mock the data for API testing.

Here, We will mock our LMS service sample response to use in our Rest Assured test.

Use Postman or swagger to make a get call to the LMS service and copy as many responses you want to use for mocking.

Verify it in jsoneditoronline.org

Using any Api mocking tool, get the mock url( I used designer.mocky.io) Note that we are not hitting the real server but replacing with the mock url.

So, your test looks like this.. (make sure to change your mock url)


package funcTesting;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import io.restassured.RestAssured;
public class PojoTestMock {
@Test
public void getPojoFromMockUrlofsimplejsonArray() throws JsonMappingException,JsonProcessingException{
//Deserialization using sample mock
// you paste your mock url
ProgramInfo[] allprogramdetails = RestAssured.given().log().all().when().get("https://run.mocky.io/v3/cf3fb516-8429-4e5e-8fc0-2cfbde6b6ff9").as(ProgramInfo[].class);
System.out.println("no of programs: "+ allprogramdetails.length);
System.out.println("Program Name: "+allprogramdetails[0].getProgramId());
System.out.println("Program Name: "+allprogramdetails[3].getProgramId());
System.out.println("Program Name: "+allprogramdetails[0].getProgramName());
System.out.println("Program Description: "+allprogramdetails[3].getProgramName());
}
}

Execute and check your results!

Explore more! Happy Learning!!

788 views

Recent Posts

See All
bottom of page