Issue
In rest-assured, when we do
given().get("/api").then().statusCode(SC_OK).content(JSON);
The error thrown is always sequential, i.e. if the status code fails, it won't check if the contentType is JSON.
Also, the error thrown is always, AssertionError (Expected : 200, Actual : 404) There is no way to understand from this, what was the actual response, it will be printed on the STDOUT if we enable logging, but it's not available any other way.
Is there any way to build or setup something like how we can implement Filter
which we can provide at request building to intercept the setting before the actual call
I have a rest api framework where most of the validations are done using ValidatableResponse
i.e. using .then()...;
and not by creating expectations of the response at request building time.
I wish to intercept a specific type of failures, i.e. if the status code failing is 50_ when we expected 200 or anything else, so that the actual failure can be posted in the test failure reason
I did raise github issue
But I'm not sure if that will be implemented anytime soon. I'm not able to find anything in the documentations as well.
Solution
I was able to achieve this by delegating the Response
and the ValidatableResponse
Interface implementations
Basically
public class DelegateResponse implements Response {
Response response;
DelegateResponse(Response response){
this.response = response;
}
.
.
.
// Override and delegate other functions normally, but in the below call, delegate further
@Override
ValidatableResponse then(){
return new DelegateValidatableResponse(response.then(), response);
}
}
public class DelegateValidatableResponse implements ValidatableResponse {
ValidatableResponse validatableResponse;
Response response;
DelegateValidatableResponse(ValidatableResponse validatableResponse,Response response) {
this.validatableResponse = validatableResponse;
this.response = response;
}
.
.
.
// Override and delegate other functions similarly and wrap with try catch
// This gives us access to Response object if an exception is thrown and we have more details
// than just the String "Expected status code 200 but was 500"
@Override
public ValidatableResponse statusCode(Matcher<? super Integer> expectedStatusCode) {
try {
return validatableResponse.statusCode(expectedStatusCode);
} catch (Throwable exception) {
throw new ApiValidationError(response, requestSpec, responseSpec, exception);
}
}
}
Answered By - nishantvas