简体   繁体   中英

How to validate a response and extract a value from Response body in Rest Assured?

I know how to extract a value from Response body and also how to validate a field from response body, but what the problem is

void postRequest() {
    Response id = given()
            .auth()
            .preemptive()
            .basic(username,password)
            .contentType(ContentType.JSON)
            .body(----- some JSON body ------)
            .when()
            .post(baseurl+"postRequest")
            .then()
            .contentType(ContentType.JSON)
            .extract()
            .path("id")
            ;
}

with this, I can extract the value that I want to and saved it into a variable "id" and use it for further API requests.

response
    .then()
    .log().ifValidationFails(LogDetail.ALL, true)  # I NEED TO PRINT REQUEST PARAMS TOO IF IT FAILS
    .assertThat()
    .statusCode(200)
    ;

If I did the above approach, I couldn't get to validate the response body since we didn't save the response to a variable.

I want to do both in one go. Also, I tried the opposite too, where I validated the response body first, but I couldn't save the "id" since we can't convert ValidatableResponse to Response or vice versa. I do not want to print the request params unless the request fails.

Help me find a way with this.

As far as I understand, you want both: validate response and extract value (for other API) in one chain command. This is example:

int id = given().post()
        .then()
        .log().ifValidationFails()
        .assertThat()
        .contentType(ContentType.JSON)
        .statusCode(200)
        .body("id", equalTo("test"))
        .extract()
        .response()
        .path("id");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM