Print response body when statusCode assert fails with restassured
Asked Answered
B

2

14

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());
}
Burnell answered 25/7, 2018 at 10:43 Comment(3)
How can I adapt duplicated question's answer to my problem, as I'm using Restassured and not HttpURLConnection ?Racquelracquet
One solution was to use secured().when().post(url).then().log().ifValidationFails(LogDetail.BODY).statusCode(200); sourceRacquelracquet
I know some time has passed, but this question is in no way a duplicate of the linked one in the close reason. That's talking about a different library and doing a different thing.Slake
B
21

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

Burnell answered 10/2, 2020 at 13:15 Comment(1)
works flawlessly!Promiscuity
D
-1

You can add a message to the assertion when test fails:

.statusCode(describedAs("The test fails because ...", is(200)))
Discriminative answered 27/7, 2020 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.