Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print response body when statusCode assert fails with restassured

I'm using Hamcrest to unit test a REST API.

When I send a request, I often check for a 200 status code like this :

public void myTest() {
    url = "route/to/my/rest/api/";
    secured().when().get(url).then().statusCode(200);
}

But when I get a wrong code status, I only get an assertion error. Is there a way to automatically dump the response body (which contains the error) when the status code doesn't match ?

The secured() method :

public RequestSpecification secured() {
    return given().header("Authorization", "Bearer " + getAuth());
}
like image 930
matthiasbe Avatar asked Jul 25 '18 10:07

matthiasbe


People also ask

How do I print a response body in RestAssured?

In the below code we will simply read the complete Response Body by using Response. getBody() and will print it out on the console window. Note: Response. body() method does exactly the same thing.

How do you read a JSON response body using rest assured?

We can parse JSON Response with Rest Assured. To parse a JSON body, we shall use the JSONPath class and utilize the methods of this class to obtain the value of a specific attribute. We shall first send a GET request via Postman on a mock API URL and observe the Response body.

How do I extract status code from RestAssured response?

We can get response status code using getStatusCode() method which is written in the Response interface in the package io. restassured. response. That method returns an integer value and and above test verify the value of this integer using assertEquals() method in TestNG.


1 Answers

As I mentioned in the comments I used the following

secured().when().post(url).then().log().ifValidationFails(LogDetail.BODY).statusCode(200);

You can find the source in the documentation

like image 91
matthiasbe Avatar answered Oct 02 '22 17:10

matthiasbe