top of page

REST Assured Tutorial

Validate Response Status

How To Validate Response Status Using REST Assured ?

REST APIs have Status which is consist of three parts represented as a string known as Status Line.In this string the first part represents HTTP protocol version, second one represents Status Code and the third one reperesents the string value of status code. ​ To fetch this status line, Rest Assured provides an interface 'Response' that have many methods, of which we will use methods getStatusLine() and getStatusCode() for accessing its status :

io.restassured.response.Response response= httpRequest.get("/Books"); response.getStatusLine() response.getStatusCode()

Furthermore, we will apply assertions on them to validate/verify the results :

import org.testng.Assert; Assert.assertEquals(response.getStatusLine(), "HTTP/1.1 200 OK", "Incorrect Status Line Returned"); Assert.assertEquals(response.getStatusCode(), 200, "Incorrect Status Code Returned");

Let's take an example - Validating Response Status Code and Status Line :

package apiTesting; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import io.restassured.RestAssured; import io.restassured.specification.RequestSpecification;

public class ValidateResponseStatus { RequestSpecification httpRequest; io.restassured.response.Response response;

@Test public void validateResponseStatusCode() { // Validate Status Code Assert.assertEquals(response.getStatusCode(), 200, "Incorrect Status Code Returned"); } @Test public void validateResponseStatusLine() { // Validate Status Line Assert.assertEquals(response.getStatusLine(), "HTTP/1.1 200 ", "Incorrect Status Line Returned"); } @BeforeClass public void apiSetUP() { RestAssured.baseURI = "http://localhost:8080/msg/webapi"; httpRequest = RestAssured.given(); response = httpRequest.get("/userProfiles"); } }

Output :

[RemoteTestNG] detected TestNG version 6.14.3 [TestNGContentHandler] [WARN] It is strongly recommended to add "<!DOCTYPE suite SYSTEM "" >" at the top of your file, otherwise TestNG may fail or not work as expected. PASSED: validateResponseStatusCode PASSED: validateResponseStatusLine =============================================== Default test Tests run: 2, Failures: 0, Skips: 0 =============================================== =============================================== Default suite Total tests run: 2, Failures: 0, Skips: 0 ==============================================

Change "HTTP/1.1 200 " or "200" with some other values and try to run the test, you will see error messges as assertions would be getting failed. ​
Refer next page Validate Response Header​
bottom of page