13

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());
}
Matthias Beaupère
  • 1,731
  • 2
  • 17
  • 44
  • 1
    How can I adapt duplicated question's answer to my problem, as I'm using Restassured and not HttpURLConnection ? – Matthias Beaupère Jul 25 '18 at 12:34
  • 4
    One solution was to use `secured().when().post(url).then().log().ifValidationFails(LogDetail.BODY).statusCode(200);` [source](https://github.com/rest-assured/rest-assured/wiki/Usage#log-if-validation-fails) – Matthias Beaupère Jul 25 '18 at 15:26
  • 2
    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. – DaveyDaveDave Jan 24 '20 at 11:16

2 Answers2

20

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

Matthias Beaupère
  • 1,731
  • 2
  • 17
  • 44
0

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

.statusCode(describedAs("The test fails because ...", is(200)))
Norayr Sargsyan
  • 1,737
  • 1
  • 12
  • 26