Friday, August 7, 2020

Data Driven Testing for REST POST Method

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.

     Now at first, we will read the data from Excel file and then will feed to Json request/payload.

    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 strTestDataPath = "C:/Testdata/TestData_CreateEmployee.xls";
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();
             }finally{
                   wrkBookOBj.Close();
                  }   

     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.


We can use either of one way or options to configure the josn request. 
 
Option I:- Use Payload directly inside the code and passing JSON request  as string.
String payload ="{"name":"","salary":"","address":{"Street":"","PostCode":"","Country":""   }}";
        JSONParser jsonParser = new JSONParser();
        jsonObject = (JSONObject) jsonParser.parse(payload);

Option II:- Put the Json request or payload inside the '.json' file and read it from file reader.
FileReader reader = new FileReader("C:/Payloads/CreateEmployee.json");       
        JSONParser jsonParser = new JSONParser();

        jsonObject = (JSONObject) jsonParser.parse(reader);


    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;

}

    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 strTestDataPath = "C:/Testdata/TestData_CreateEmployee.xls";
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.
            JSONObject jsonObj = fnUpdatePayload(strName, strSalary, strStreet
                                                                      strPostCode, strCountry);
 
    //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.POST,"/api/v1/create");
      
    //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();
            }finally{
                   wrkBookOBj.Close();
                  }  

And at the end our final code will looks something like this.

**************************************************************************    

**************************************************************************    

package test.rest.practice;
 
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();   
             
              //The below line of code is to define type of request we are sending.
               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);
                           resObj = httpRequest.request(Method.POST,"/api/v1/create");
                           
                           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 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("]","");
                    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.


                         That’s all Folks.