简体   繁体   中英

In REST Assured, how can I check if a field is present or not in the response?

How can I make sure that my response, let's say it is in JSON, either contains or does not contain a specific field?

when()
    .get("/person/12345")
.then()
    .body("surname", isPresent()) // Doesn't work...
    .body("age", isNotPresent()); // ...But that's the idea.

I'm looking for a way to assert whether my JSON will contain or not the fields age and surname .

You can use the Hamcrest matcher hasKey() (from org.hamcrest.Matchers class) on JSON strings as well.

when()
    .get("/person/12345")
.then()
    .body("$", hasKey("surname"))
    .body("$", not(hasKey("age")));

You can use equals(null) like this:

.body("surname", equals(null))

If the field does not exists it will be null

Check whetever field is null. For example:

    Response resp = given().contentType("application/json").body(requestDto).when().post("/url");
    ResponseDto response = resp.then().statusCode(200).as(ResponseDto.class);
    Assertions.assertThat(response.getField()).isNotNull();

Using: import static org.junit.Assert.assertThat;

Your could then: assertThat(response.then().body(containsString("thingThatShouldntBeHere")), is(false));

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