Showing posts with label RestAssured POST method. Show all posts
Showing posts with label RestAssured POST method. Show all posts

Rest Assured Post method with data from Excel

 

 

Feature File

Feature: Rest Assured API import from Excel

 

Scenario Outline: Validate rest assured API import from Excel

Given User adds body from Excel<excelFilePath> for POST method for<SheetName> and<RowNumber>

And User executes the API

Then User validates the data

 

Examples:

|excelFilePath                      |SheetName|RowNumber|

|C:\JavaProject\...\RestAssured.xlsx|EmpInfo_1|2|

|C:\JavaProject\...\RestAssured.xlsx|EmpInfo_1|3|


Test Runner

package testRunner;

 

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;

import cucumber.api.junit.Cucumber;

 

 

@RunWith(Cucumber.class)

@CucumberOptions(

            

 

features = "C:\\JavaProject\\Badri's_WorkSpace\\TestPractice\\resource\\features\\RestAssured_POST_ReadFromExcel.feature",

glue = {"restAssuredTest"},

format = {"pretty", "pretty:test-output/prettyFormat.txt","usage:test-output/usageFormat.json","rerun:test-output/rerun.txt", "html:test-output","json:test-output/jsonReport.json","junit:test-output/junitReport.xml"},

 

monochrome = true,

dryRun = false,

strict = true

//tags

             )

 

public class TestRunner {

      

 

}

 

Method Read from Excel

package utility;

 

import java.util.HashMap;

 

import org.apache.poi.ss.usermodel.DataFormatter;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

public class ReadFromExcelforRestAssured {

       // Get test data from the row number and put in hashmap

       public HashMap<Object, Object> readExcelFromRowNumber(String excelFilePath, String excelSheetName,

                    int rowToExecute) {

             HashMap<Object, Object> map = new HashMap<>();

             rowToExecute = rowToExecute - 1;

             try {

 

                    XSSFWorkbook workbook = new XSSFWorkbook(excelFilePath);

                    XSSFSheet sheetName = workbook.getSheet(excelSheetName);

 

                    // Find row number

                    int numberOfRow = sheetName.getPhysicalNumberOfRows();

                    System.out.println("Number of Rows from readExcelFromRowNumber : " + numberOfRow);

 

                    // Find column number

                    int lastRow = sheetName.getLastRowNum();

                    Row row = sheetName.getRow(lastRow); // import "org.apache.poi.ss.usermodel.Row" at this point.

                    int lastCell = row.getLastCellNum();

                    System.out.println("Last Cell ie Number of columns is = " + lastCell);

 

                    int colNumber = 0;

                    for (int i = 0; i < lastCell; i++) {

                           colNumber = i;

                           DataFormatter formatter = new DataFormatter();

                           Object cellTitle = formatter.formatCellValue(sheetName.getRow(0).getCell(colNumber));

                           Object cellValue = formatter.formatCellValue(sheetName.getRow(rowToExecute).getCell(colNumber));

                           map.put(cellTitle, cellValue);

                           System.out.println("The cell title is : " + cellTitle);

                           System.out.println("The cell value is : " + cellValue);

                           System.out.println("Key: " + cellTitle + ", " + "Value: " + cellValue);

 

                    }

                    System.out.println("The map is : " + map);

 

             } catch (Exception e) {

 

                    System.out.println(e.getMessage());

                    System.out.println(e.getCause());

                    e.printStackTrace();

             }

             return map;

       }

}

 

Step Definition

package restAssuredTest;

 

import cucumber.api.java.Before;

import cucumber.api.java.en.And;

import cucumber.api.java.en.Given;

import cucumber.api.java.en.Then;

import io.restassured.http.ContentType;

import io.restassured.response.Response;

import utility.ReadFromExcelforRestAssured;

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

import java.util.HashMap;

import org.json.simple.JSONObject;

 

public class RestAssured_POST_ReadFromExcel {

       Response response ;

       String responseBoydAsString;

       HashMap<Object, Object> map;

      

       @Before()

       public void beforeMethod() {

       given().

       header("Key","value").//to give header

       //header("Key","value").accept(null)//extra informaton in the header

       param("key","value");//to give parameter

       }

      

       @Given("^User adds body from Excel(.*) for POST method for(.*) and(.*)$")

       public void readDataFromExcel(String excelFilePath, String sheetName, int rowNumber) {

             System.out.println("This step is done below.");

             ReadFromExcelforRestAssured xl = new ReadFromExcelforRestAssured();

             map = xl.readExcelFromRowNumber(excelFilePath,sheetName, rowNumber);

       }

      

 

       @And("^User executes the API$")

       public void executeAPI() {

 

             JSONObject request = new JSONObject();

             request.put("name", map.get("name"));

             request.put("job", map.get("job"));

             System.out.println("request.toJSONString = "+request.toJSONString());

             given().

                    header("Content-Type","application/json"). // use header here if needed , header has Key , value pair

                    contentType(ContentType.JSON).

                    accept(ContentType.JSON).

                    body(request.toJSONString()).

             when()

                    .post("https://reqres.in/api/users").

             then()

                    .statusCode(201)

                    .body("name",equalTo(map.get("name")))

                    .body("job",equalTo(map.get("job")))//;

                    .header("Server",equalTo("cloudflare"))//this is from response header

                    .log().all();//this will print all the response in the console in the same format like in postman

 

       }

      

       @Then("^User validates the data$")

       public void validateDataFromExcel() {

            

       }

 

}

 

Output:

Below output is for  “.log().all()” only

HTTP/1.1 201 Created

Date: Thu, 05 May 2022 10:11:04 GMT

Content-Type: application/json; charset=utf-8

Content-Length: 84

Connection: keep-alive

X-Powered-By: Express

Access-Control-Allow-Origin: *

Etag: W/"54-fSbFNciRUYPEoQdH7hU+xO8oKdk"

Via: 1.1 vegur

CF-Cache-Status: DYNAMIC

Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"

Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=xFEPdGkFw1Yh2lwVndgAOnOiBl2f2UNro17R1iOuxr3KBPvGzAE%2FsGo9IKV0QhDhyK1X3acIKn%2F67%2BcFSk1komO9RJns9foH1ZQ9Uc%2BpewnfKiHZIwUg51qVU%2F8%3D"}],"group":"cf-nel","max_age":604800}

NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}

Server: cloudflare

CF-RAY: 7068b09bea8947fe-SIN

alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400

 

{

    "name": "Hari",

    "job": "Technician",

    "id": "531",

    "createdAt": "2022-05-05T10:11:04.342Z"

}

 

 

 

 

HTTP/1.1 201 Created

Date: Thu, 05 May 2022 10:11:05 GMT

Content-Type: application/json; charset=utf-8

Content-Length: 87

Connection: keep-alive

X-Powered-By: Express

Access-Control-Allow-Origin: *

Etag: W/"57-OJvnaX8QBWX/tqbD7Ceq1jZ8O9U"

Via: 1.1 vegur

CF-Cache-Status: DYNAMIC

Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"

Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=Uk8XvjRI7umU7%2FEHyudN6K89mYNdOx60e9i%2BeFXymXDEuYTi%2BC6bUAskdlhCOkDX5btLNAznsfKD%2Fr8UdANrd6xq6gQMNfT5K%2FaExDGE3VYc9nIStkotQzhwQCA%3D"}],"group":"cf-nel","max_age":604800}

NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}

Server: cloudflare

CF-RAY: 7068b0a78b752ee3-SIN

alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400

 

{

    "name": "Gopal1",

    "job": "Electrician",

    "id": "489",

    "createdAt": "2022-05-05T10:11:05.827Z"

}

 

 Excel