Validate Response Status using Rest Assured

The first line returns from the HTTP Response is known as Status Line. The status line has a status code which is also useful to determine if HTTP Response is successful or not. The status line is composed of three substrings as “Http protocol version/Status code/ Status code string value” and from here we get the status code. The Response object provides mechanisms to read Status. The response is an interface that resides in the package: io.restassured.response.

 
Method1:

Method getstatusCode() and .getStatusLine() is used to get the status code and status line of the response, respectively. The method getstatusCode() returns an integer as input which would be validated against the response code and the method .getStatusLine() returns a () returns a String as input which would be validated against the response status line.


// Get the status code of the response

int statusCode = response.getStatusCode();


//Get the status line of the response

String statusString = response.getStatusLine();


// Validate the response code against the expected status code

Assert.assertEquals(statusCode, 200);


// Validate the response line against the expected status line

Assert.assertEquals(statusString, “HTTP/1.1 200 OK”);


Complete Example Code

@Test

public void
GetDetail() {


RestAssured.baseURI = "https://petstore.swagger.io/v2/store/order";
RequestSpecification httpRequest = RestAssured.given();
Response response = httpRequest.get("/1");

// Get the status code from the Response.
int statusCode = response.getStatusCode();

// Assert that correct status code is returned.
Assert.assertEquals(statusCode, 200,
"Correct status code returned");
}
}

 

Method 2:

It can also be verified through a shorter version of code to validate the status code and status line with REST Assured. Any validation to be performed can be written after .then().


// Get and Validate the response code

get("https://petstore.swagger.io/v2/store/order/1")
.then().assertThat().statusCode(200);


// Get and Validate the response line

get("https://petstore.swagger.io/v2/store/order/1")
.then().assertThat().statusLine("HTTP/1.1 200 OK");
 

Complete Example Code

@Test

public void GetDetail() {


RestAssured.baseURI = "https://petstore.swagger.io/v2/store/order";

RestAssured.given()

.when()

.get("/1")

.then().assertThat().statusCode(200);

}

 

Practice Yourself: Validate the expected status line using both methods.