Sunday 24 November 2019

Rest Assured: Map response to a model object

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

Step 2: Convert Response to a model class.
Employee emp = response.as(Employee.class);

Employee.java
package com.sample.app.model;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

}

App.java
package com.sample.app;

import static io.restassured.RestAssured.given;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.sample.app.model.Employee;

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/3").then().assertThat().statusCode(200).and()
    .contentType(ContentType.JSON).extract().response();

  Employee emp = response.as(Employee.class);

  assertEquals(emp.getId(), 3);
  assertEquals(emp.getFirstName(), "Purna Chandra");
  assertEquals(emp.getLastName(), "Rao");
 }

}

How to map list of employees to a model class?
Employee[] emps = response.as(Employee[].class);

TestApp.java    
package com.sample.app;

import static io.restassured.RestAssured.given;

import org.junit.Test;

import com.sample.app.model.Employee;

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();

  Employee[] emps = response.as(Employee[].class);

  for (Employee emp : emps) {
   System.out.println(emp.getId());
  }
 }

}

Output
1
2
3
4
5
6
7
8
9


Previous                                                    Next                                                    Home

No comments:

Post a Comment