PUT REST to API Testing with Data Driven approach:
PUT method is used to amend or modify
the existing record or data in the system. PUT methods searches for the record
in system to match with the unique querying in request. If unique key matches
with record preset in the system, then PUT method performs actions meaning it
updates the record.
In the last post we have seen how to work on POST
method using Rest Assured with Data driven approach, reading input data from
external source e.g. excel file.
In this post we will see the use of http PUT
method for REST API’s using Rest Assured with Data driven approach.
As basic rule
we need to have base URI of REST services for REST API testing.
Here in this post I will be using sample URI and payload as
below.
URI :- http://dummy.restapiexample.com/api/v1/update/{key}
Sample Payload :-
{
"name":"",
"salary":"",
"age":""
}
For the above payload we
need to pass the value reading/getting it from external sources like XML,
Excel. Here we are using excel file.
We used Excel file and created test data in that and read those
values and send it to Json request.
Below is table created in excel file as my test data for above Json request (Payload).
SINo | EmpCode | Name | Salary | EmpAge | ExpStatusCode | ExpFieldName | ExpFieldValue |
1 | 2818 | Sandeep | 23123 | 35 | 200 | message;status;data.name;data.age;data.salary | Successfully! Record has been updated.;success;Sandeep;35;23123 |
2 | 2829 | LgSoftTest | 31232 | 46 | 200 | message;status;data.name;data.salary | Successfully! Record has been updated.;success;LgSoftTest;31232 |
3 | 2945 | GoogleBlogger | 23112 | 38 | 200 | message;status | Successfully! Record has been updated.;success |
4 | 3038 | Blogger | 53123 | 55 | 200 | message;status;data.name;data.salary | Successfully! Record has been updated.;success;Blogger;53123 |
From above table we are reading input data for Json request from
‘EmpCode’, ‘Name’, ‘Salary’ and ‘EmpAge’ columns. Remaining columns ‘ExpStatusCode’, ‘ExpFieldName’ and
‘ExpFieldValue’ are for validating the response.
Now at first, we will read the data from Excel
file and then will feed to Json request/payload.
Here we are retrieving data from column and row wise and assigning it to a variable. Since column starts from ‘0th’(zero) position here I am reading data from 1st column i.e. “EmpCode” column and so on till last column. Same way row starts from ‘0th’(zero) position here I am reading data from 1st row contains value “EID2818” and so on till last row we will read the data.
String strTestDataPath = "C:/Testdata/ TestData_UpdateEmployee.xls";
String strTestDataSheet = "EmpData";
try {
wrkBookOBj = Workbook.getWorkbook(new File(strTestDataPath));
sheet = wrkBookOBj.getSheet(strTestDataSheet);
int rRows = sheet.getRows();
int i = 0;
for(i=1;i<=rRows-1;i++) { //Rows loop
String strEmpCode = sheet.getCell(1,i).getContents();
String strName = sheet.getCell(2,i).getContents();
String strSalary = sheet.getCell(3,i).getContents();
String strAge = sheet.getCell(4,i).getContents();
String strExpStatusCode = sheet.getCell(5,i).getContents();
String strExpFieldNames = sheet.getCell(6,i).getContents();
String strExpFieldValues = sheet.getCell(7,i).getContents();
JSONObject jsonObj = fnUpdatePayload(strName, strSalary, strAge);
httpRequest.body(jsonObj);
resObj = httpRequest.request(Method.PUT,"/api/v1/update/"+strEmpCode);
if(String.valueOf(resObj.getStatusCode()).contentEquals(strExpStatusCode)) {
fnCheckResult(strExpFieldNames, strExpFieldValues, resObj );
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
wrkBookOBj.close();
As of now we have got our data from excel file, now it’s time to send these values to Json request. To do that we need to use Json object to parse it and update with test data. So, I have added below code to update the data and kept it in a method because we can re-use this method for different set of data inside loop.
Below code for configure Json request.
We can use either of one way or options to configure the josn
request.
jsonObject = (JSONObject) jsonParser.parse(payload);
JSONParser jsonParser = new JSONParser();jsonObject = (JSONObject) jsonParser.parse(reader);
JSONObject jsonObject = null;
try {
FileReader reader = new FileReader("C:/Payloads/UpdateEmployee.json");
JSONParser
JSONParser jsonParser = new JSONParser();
jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObject.put("name", strName);
jsonObject.put("salary", strSalary);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return jsonObject;
This method updates the Json file as per the values received
from the method arguments and returns the Json object. This Json object we can
use it in our PUT method. So, now I am going use this method in my above code where
I am reading the data from excel.
String strTestDataSheet = "EmpData";
try {
wrkBookOBj = Workbook.getWorkbook(new File(strTestDataPath));
sheet = wrkBookOBj.getSheet(strTestDataSheet);
int rRows = sheet.getRows();
int i = 0;
for(i=1;i<=rRows-1;i++) { //Rows loop
String strEmpCode = sheet.getCell(1,i).getContents();
String strName = sheet.getCell(2,i).getContents();
String strSalary = sheet.getCell(3,i).getContents();
String strAge = sheet.getCell(4,i).getContents();
String strExpStatusCode = sheet.getCell(5,i).getContents();
String strExpFieldNames = sheet.getCell(6,i).getContents();
String strExpFieldValues = sheet.getCell(7,i).getContents();
JSONObject jsonObj = fnUpdatePayload(strName, strSalary, strAge);
httpRequest.body(jsonObj);
resObj = httpRequest.request(Method.PUT,"/api/v1/update/"+strEmpCode);
if(String.valueOf(resObj.getStatusCode()).contentEquals(strExpStatusCode)) {
fnCheckResult(strExpFieldNames, strExpFieldValues, resObj );
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
wrkBookOBj.close();
}
//The below line of code uses name, salary and age as arguments for ‘fnUpdatePayload’ method and gets updated Json request and returns as Json object. JSONObject jsonObj = fnUpdatePayload(strName, strSalary, strage);
//Pass the above returned json object to body.
RequestSpecification httpRequest.body(jsonObj);
/Send the request and pass the create the data using POST method. Also reads the response using response object ‘resObj’ ‘object Response resObj = httpRequest.request(Method.PUT,"/api/v1/update/"+strEmpCode);
//Based on the success response check for status code 200. If
present and validate expected results comparing it from expected Vs actual.
if(String.valueOf(resObj.getStatusCode()).contentEquals(strExpStatusCode)) {
//Here we are passing expected field name, expected field
values and response object as arguments to validate expected Vs actual results
fnCheckResult(strExpFieldNames, strExpFieldValues, resObj );
}
} //Rows loop Ends Here
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
And at the end our final code will looks something like this.
***********************************************************
***********************************************************
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class HTTPPUTTestREST {
public static void main(String[] args) throws InterruptedException{
Workbook wrkBookOBj = null; Sheet sheet = null;
RequestSpecification httpRequest = null; Response resObj = null;
String strExpFieldNames = null;
String strExpFieldValues = null; String strExpStatusCode = null;
String strName = null; String strSalary = null; String strAge = null;
String strEmpCode = null;
String strTestDataPath = " C:/Testdata/ TestData_UpdateEmployee.xls ";
String strTestDataSheet = "EmpData";
RestAssured.baseURI = "http://dummy.restapiexample.com";
httpRequest = RestAssured.given();
httpRequest.header("Content-Type","application/json");
try {
wrkBookOBj = Workbook.getWorkbook(new File(strTestDataPath));
sheet = wrkBookOBj.getSheet(strTestDataSheet);
int rRows = sheet.getRows();
int i = 0;
for(i=1;i<=rRows-1;i++) { //Rows loop
strEmpCode = sheet.getCell(1,i).getContents();
strName = sheet.getCell(2,i).getContents();
strSalary = sheet.getCell(3,i).getContents();
strAge = sheet.getCell(4,i).getContents();
strExpStatusCode = sheet.getCell(5,i).getContents();
strExpFieldNames = sheet.getCell(6,i).getContents();
strExpFieldValues = sheet.getCell(7,i).getContents();
JSONObject jsonObj = fnUpdatePayload(strName, strSalary, strAge);
httpRequest.body(jsonObj);
resObj = httpRequest.request(Method.PUT,"/api/v1/update/"+strEmpCode);
if(String.valueOf(resObj.getStatusCode()).contentEquals(strExpStatusCode)) {
fnCheckResult(strExpFieldNames, strExpFieldValues, resObj );
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
wrkBookOBj.close();
}
}
//****************************************************************************************************************/
public static JSONObject fnUpdatePayload(String strName, String strSalary, String strAge) {
JSONObject jsonObject = null;
try {
FileReader reader = new FileReader(System.getProperty("user.dir")+"/Payloads/UpdateEmployee.json");
JSONParser jsonParser = new JSONParser();
jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObject.put("name", strName);
jsonObject.put("salary", strSalary);
jsonObject.put("age", strAge);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return jsonObject;
}
//****************************************************************************************************************/
public static void fnCheckResult(String ExpField, String ExpValues, Response resObj) {
String strExpFieldName[] = ExpField.split(";");
String strExpFieldValue[] = ExpValues.split(";");
for(int x = 0;x<=strExpFieldName.length-1;x++) {
String extFieldName = strExpFieldName[x];
String extFieldValue = strExpFieldValue[x];
String strActFieldValues = resObj.jsonPath().get(extFieldName).
String strActFieldValue[] = strActFieldValues.split(",");
boolean temp = false;
for(int z = 0;z<=strActFieldValue.length-1;z++) {
if(((strActFieldValue[z].trim()).equalsIgnoreCase(extFieldValue.trim()))) { System.out.println("PASS");
temp = true;
break;
}else if(extFieldValue.trim().equalsIgnoreCase("NotNull")) {
if((strActFieldValue[z].trim())!=null) {
System.out.println("PASS");
temp = true;
break;
}
}
if((!temp) && z == strActFieldValue.length-1) { System.out.println("FAIL");
}
}
if(temp && x==strExpFieldName.length-1) {
break;
}
}
}
}
Still have any open questions put them in comments i will try best to resolve.