Search code examples
javarestunit-testingrest-assuredhamcrest

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());
}

Solution

  • 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