简体   繁体   English

在REST Assured中,如何检查响应中是否存在字段?

[英]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? 我怎样才能确保我的响应(包括它是JSON) 包含不包含特定字段?

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 . 我正在寻找一种方法来断言我的JSON是否包含字段agesurname

You can use the Hamcrest matcher hasKey() (from org.hamcrest.Matchers class) on JSON strings as well. 您也可以在JSON字符串上使用Hamcrest匹配器hasKey() (来自org.hamcrest.Matchers类)。

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

You can use equals(null) like this: 您可以像这样使用equals(null):

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

If the field does not exists it will be null 如果该字段不存在,则它将为null

Check whetever field is null. 检查wheedver字段是否为空。 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; 使用: import static org.junit.Assert.assertThat;

Your could then: assertThat(response.then().body(containsString("thingThatShouldntBeHere")), is(false)); 然后你可以: assertThat(response.then().body(containsString("thingThatShouldntBeHere")), is(false));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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