Rest Assured Flashcards
REST Assured
(DSL) API used for writing automated tests for RESTful APIs.
Advantages of using REST Assured
It provides a lot of helper methods and abstraction layers that remove the need for writing a lot of boilerplate code for connections, sending a request, and parsing a response.
The DSL provided by it, increases the readability of the code.
There is a seamless integration with testing frameworks like Junit or TestNG and other continuous integration tools.
JsonPath and XmlPath
JsonPath and XmlPath are the query languages which help to extract (parse server response for validation) data from the JSON and XML document
Sample Maven dependency
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.3.0</version>
</dependency>
a DSL expression request using the Given/When/Then
given()
when()
then()
given()
used in building the DSL expression request with any additional information like
headers,
params,
message body,
authentication, etc.,
before making any HTTP Request
RestAssured.given()
.header(“header1”,”value1”)
.header(“header2”, “value2”)
.param(“param1”,”paramValue”)
.body(body)
.post(url);
example, no extra information is added to the request builder before making a GET request.
RestAssured.given()
.get(url);
when()
when() can be used with given() or independently in the DSL expression.
RestAssured.given()
.param(“firstName”, “John”)
.param(“lastName”, “Doe”)
.when()
.get(“/greet”);
when() is used with given() in the DSL expression to pass some parameters with the request.
RestAssured.given()
.param(“firstName”, “John”)
.param(“lastName”, “Doe”)
.when()
.get(“/greet”);
then()
It is always used with either given(), when(), or with both methods in the DSL expression. It returns a validatable response.
RestAssured.given().
.param(“firstName”, “John”)
.param(“lastName”, “Doe”)
.when()
.get(“/greet”)
.then()
.body(“greeting”, equalTo(“John Doe”));
Example 1 – Fetch all student records
import static org.hamcrest.Matchers.equalTo;
import org.testng.annotations.Test;
import static org.testng.Assert.*
import io.restassured.response.Response;
import io.restassured.RestAssured;
String url = “http://ezifyautomationlabs.com:6565/educative-rest/students”;
Response response = RestAssured.given().get(url).andReturn();
response.getBody().prettyPrint();
assertEquals(response.getStatusCode(), 200, “http status code”);
makes a GET request and returns a Response object
Response response = RestAssured.given().get(url).andReturn();
prints the response body in the JSON format
response.getBody().prettyPrint();
asserts the response status code as 200
assertTrue(response.getStatusCode()==200);
gets the list of all Student Ids from the response body and assert that one of the Id is 101
assertTrue(response.getBody().jsonPath().getList(“id”).contains(101));