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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43045226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:38:31  来源:igfitidea点击:

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

javarestrest-assured

提问by juliaaano

How can I make sure that my response, let's say it is in JSON, either containsor does not containa 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 ageand surname.

我正在寻找一种方法来断言我的 JSON 是否将包含字段agesurname

回答by J. N

You can use equals(null) like this:

您可以像这样使用 equals(null) :

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

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

If the field does not exists it will be null

如果该字段不存在,它将为空

回答by Marcin Tarka

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();

回答by Luciano van der Veekens

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

您也可以在 JSON 字符串上使用 Hamcrest 匹配器hasKey()(来自org.hamcrest.Matchers类)。

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

回答by ForJaysSake

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));