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());
}
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With