REST API POST Testing using Data Driven:
In REST services HTTP POST method is used to create a new record in the system. Compare to GUI, API's/services are faster in nature to create or test the system and create in large number of data. In short POST method is used for new record creation in the system.
In the last post we have
seen how to work on GET method using Rest Assured with Data driven approach,
reading input data from external source e.g. excel file.
In this post we will see
use of http POST method for REST API’s using Rest Assured with Data driven approach.
To begin with this, we need to have URI and payload to work on POST method. URI
and Payload (will be provided by developer in your project just check with
them.) Here in this post I will be using sample URI and payload as below.
URI :- http://dummy.restapiexample.com/api/v1/create
Sample Payload :-
{
"name":"",
"salary":"",
"address":{
"Street":"",
"PostCode":"",
"Country":""
}}
So, once we got both URI and payload, now we need to read and pass the data/values to the Json request. As we have seen in previous post, we used Excel file and created test data in that and read those values and sent in Json request. So same action we need to do again here also.
Below is table I have
created in excel file as my test data for above Json request (Payload).
SINo |
Name |
Salary |
Street |
PostCode |
Country |
ExpStatusCode |
ExpFieldName |
ExpFieldValue |
1 |
Sandeep |
23123 |
10 mount st |
100001 |
IND |
200 |
message;status;data.id;data.address.PostCode |
Successfully! Record has been added.;Success;NotNull;100001 |
2 |
LgSoftTest |
31232 |
100 vic road |
2145 |
AUD |
200 |
message;status;data.id;data.address.Country |
Successfully! Record has been added.;Success;NotNull;AUD |
3 |
GoogleBlogger |
23112 |
25 mants street |
400001 |
IND |
200 |
data.id |
NotNull |
4 |
Blogger |
13123 |
12 ross lane |
1640 |
NOR |
200 |
message;status;data.id;data.address.Street |
Successfully! Record has been added.;Success;NotNull;12 ross
lane |
In above table I am
reading input data for Json request from ‘Name’, ‘Salary’, ‘Street’, ‘PostCode’
and ‘Country’ columns. Remaining columns ‘ExpStatusCode’, ‘ExpFieldName’ and ‘ExpFieldValue’
are for validating the response.
Below code is used to
read the data from Excel file. Here we are retrieving data from column and row wise and
assign it to a variable. Since column starts from ‘0th’(zero)
position here I am reading data from 1st column i.e. “Name” 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 “Sandeep”
and so on till last row we will read the data.
String strTestDataSheet = "EmpData";
try {
Workbook wrkBookOBj = Workbook.getWorkbook(new File(strTestDataPath));
Sheet sheet = wrkBookOBj.getSheet(strTestDataSheet);
int rRows = sheet.getRows();
for(int i=1;i<=rRows-1;i++) { //Rows loop
String strName = sheet.getCell(1,i).getContents();
String strSalary = sheet.getCell(2,i).getContents();
String strStreet = sheet.getCell(3,i).getContents();
String strPostCode = sheet.getCell(4,i).getContents();
String strCountry = sheet.getCell(5,i).getContents();
String strExpStatusCode = sheet.getCell(6,i).getContents();
String strExpFieldNames = sheet.getCell(7,i).getContents();
String strExpFieldValues = sheet.getCell(8,i).getContents();
} //Rows loop Ends Here
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
As of now we have got
our data from excel file, now its 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.
String payload ="{"name":"","salary":"","address":{"Street":"","PostCode":"","Country":"" }}";
JSONParser jsonParser = new JSONParser();
jsonObject = (JSONObject) jsonParser.parse(payload);
FileReader reader = new FileReader("C:/Payloads/CreateEmployee.json");
JSONParser jsonParser = new JSONParser();
jsonObject = (JSONObject) jsonParser.parse(reader);
try {
FileReader reader = new FileReader("C:/Payloads/CreateEmployee.json");
JSONParser jsonParser = new JSONParser();
jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObject.put("name", strName);
jsonObject.put("salary", strSalary);
JSONObject addressObj = (JSONObject) jsonObject.get("address");
addressObj.put("Street", strStreet);
addressObj.put("PostCode", strPostCode);
addressObj.put("Country", strCountry);
} 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 post 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 {
Workbook wrkBookOBj = Workbook.getWorkbook(new File(strTestDataPath));
Sheet sheet = wrkBookOBj.getSheet(strTestDataSheet);
int rRows = sheet.getRows();
for(int i=1;i<=rRows-1;i++) { //Rows loop
String strName = sheet.getCell(1,i).getContents();
String strSalary = sheet.getCell(2,i).getContents();
String strStreet = sheet.getCell(3,i).getContents();
String strPostCode = sheet.getCell(4,i).getContents();
String strCountry = sheet.getCell(5,i).getContents();
String strExpStatusCode = sheet.getCell(6,i).getContents();
String strExpFieldNames = sheet.getCell(7,i).getContents();
String strExpFieldValues = sheet.getCell(8,i).getContents();
//The below line of code uses name, salary street, postcode and country as arguments for ‘fnUpdatePayload’ method and gets updated Json request and returns as Json object.
//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
//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)) {
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 HTTPPOSTTestREST {
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 strStreet = null;
String strPostCode = null; String strCountry = null;
String strTestDataPath = "C:/Testdata/TestData_CreateEmployee.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
strName = sheet.getCell(1,i).getContents();
strSalary = sheet.getCell(2,i).getContents();
strStreet = sheet.getCell(3,i).getContents();
strPostCode = sheet.getCell(4,i).getContents();
strCountry = sheet.getCell(5,i).getContents();
strExpStatusCode = sheet.getCell(6,i).getContents();
strExpFieldNames = sheet.getCell(7,i).getContents();
strExpFieldValues = sheet.getCell(8,i).getContents();
JSONObject jsonObj = fnUpdatePayload(strName, strSalary, strStreet,strPostCode, strCountry);httpRequest.body(jsonObj);
if(String.valueOf(resObj.getStatusCode()).contentEquals(strExpStatusCode)) {
fnCheckResult(strExpFieldNames, strExpFieldValues, resObj );
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
}
**************************************************************************
public static JSONObject fnUpdatePayload(String strName, String strSalary, String strStreet, String strPostCode, String strCountry) {
JSONObject jsonObject = null;
try {
FileReader reader = new FileReader("C:/Payloads/CreateEmployee.json");JSONParser jsonParser = new JSONParser();jsonObject = (JSONObject) jsonParser.parse(reader);jsonObject.put("name", strName);jsonObject.put("salary", strSalary);JSONObject addressObj = (JSONObject) jsonObject.get("address");addressObj.put("Street", strStreet);addressObj.put("PostCode", strPostCode);addressObj.put("Country", strCountry);
} 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).toString().replace("[","").replace("]","");
boolean temp = false;
for(int z = 0;z<=strActFieldValue.length-1;z++) {
if(((strActFieldValue[z].trim()).equalsIgnoreCase(extFieldValue.trim()))) {
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;
}
}
}
}