Search code examples
cucumberrest-assured

How to validate a REST Assured request across multiple java methods?


I am writing REST Assured tests using Cucumber.

Here is my feature file:

Given I want to GET a client

When I request a client

Then the status code is "theStatusCode"

And the id returned is "expectedClientId"

The below method is called within the Step Definition of the "And" in my feature file

public void validateResponseBody(String expectedClientId){
    RestAssured.given()
    .when()
    .get(completeURL)
    .then()
    .statusCode(Integer.parseInt(theStatusCode))
    .and()
    .body("Client.Id", equalTo(expectedClientId));
}

This method currently works, but how do I split the validation?

I.e. how can I break this up to validate the Status Code in one method, & validate the Client Id in another method without having to send the request twice?


Solution

  • Save response to variable:

    public void validate() {
        ValidatableResponse response = RestAssured.given()
            .when()
            .get(completeURL)
            .then();
    
        validateStatusCode(response, statusCode);
        validateResponseBody(response, expectedClientId);
    }
    
    public void validateStatusCode(ValidatableResponse response, String statusCode) {
        response
            .statusCode(Integer.parseInt(theStatusCode));
    }
    
    public void validateResponseBody(ValidatableResponse response, String expectedClientId) {
        response
            .body("Client.Id", equalTo(expectedClientId));
    }