Sunday 24 November 2019

Rest Assured: Extract the response as string


Step 1: Get the response object.
Response response = given().header("Accept", "application/json").header("Content-Type", "application/json").when()
.get("api/v1/employees/").then().assertThat().statusCode(200).and().contentType(ContentType.JSON)
.extract().response();

Step 2: Convert response as string.
response.asString()

TestApp.java
package com.sample.app;

import static io.restassured.RestAssured.given;

import org.junit.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;

public class TestApp {

 @Test
 public void testApp() {
  RestAssured.baseURI = "http://localhost:8080";

  Response response = given().header("Accept", "application/json").header("Content-Type", "application/json").when()
    .get("api/v1/employees/").then().assertThat().statusCode(200).and().contentType(ContentType.JSON)
    .extract().response();
  
  System.out.println(response.asString());

 }

}

If you want to extract information from the response json string, you can use JsonPath class.

Example
JsonPath jsonPath = new JsonPath(response.asString());
                 
int empId = jsonPath.get("[0].id");
String firstName = jsonPath.get("[0].firstName");
String lastName = jsonPath.get("[0].lastName");

TestApp.java
package com.sample.app;

import static io.restassured.RestAssured.given;

import org.junit.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

public class TestApp {

 @Test
 public void testApp() {
  RestAssured.baseURI = "http://localhost:8080";

  Response response = given().header("Accept", "application/json").header("Content-Type", "application/json")
    .when().get("api/v1/employees/").then().assertThat().statusCode(200).and().contentType(ContentType.JSON)
    .extract().response();

  JsonPath jsonPath = new JsonPath(response.asString());

  int empId = jsonPath.get("[0].id");
  String firstName = jsonPath.get("[0].firstName");
  String lastName = jsonPath.get("[0].lastName");

  System.out.println("empId : " + empId);
  System.out.println("firstName : " + firstName);
  System.out.println("lastName : " + lastName);

 }

}


Run TestApp as Junit Test, you will see below messages in console.
empId : 1
firstName : Deepak
lastName : Moud


Previous                                                    Next                                                    Home

No comments:

Post a Comment