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
In REST Assured, how can I check if a field is present or not in the response?
提问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 是否将包含字段age和surname。
回答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
回答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));