Search code examples
seleniumcucumberrest-assuredweb-api-testing

How to pass data across cucumber steps (Test Automation rest assured API test)?


I have created an api test which hits an endpoint and receives a response back however I'm struggling to use this response within another cucumber step.

My first step uses the following method:

public Response booking(SharedStepData sharedStepData, String path, BookingType bookingType) throws IOException {
    String url = "https://example.net." + System.getProperty("endpoint") + "/v10/" + path + "Booking";

    RestAssured.useRelaxedHTTPSValidation();
    String payload = createBookingPayload(sharedStepData, bookingType);
    Response response = RestAssured
            .given().contentType(ContentType.JSON)
            .log().all()
            .body(payload)
            .when().post(url)
            .thenReturn();

    ResponseBody body = response.getBody();;
    return response;
}

I know need to save this response and then use it within another step method to perform another action, such as using specific data from the response to hit another endpoint, any ideas?


Solution

  • You can use the encapsulation logic here and can access the variable from other class

    public class Test{
    
        private String bookingResponse;
    
        public String getBookingResponse(){
            return bookingResponse;
        }
    
        public void setBookingResponse(String response){
            bookingResponse=response;
        } 
    }
    

    After Calling the first method, you can update the bookingResponse value as below

    Test test=new Test();
    
    test.setBookingResponse(<<Call your first Response Method>>);
    

    Whenever you want to access the above response, then you can use the test.getResponse() method. It will give the above response, if you are using the same Test class instance.