Java 在REST Assured中,如何检查响应中是否存在字段?
我如何确保我的响应(假设是JSON响应)包含或不包含特定字段Java 在REST Assured中,如何检查响应中是否存在字段?,java,rest,rest-assured,Java,Rest,Rest Assured,我如何确保我的响应(假设是JSON响应)包含或不包含特定字段 when() .get("/person/12345") .then() .body("surname", isPresent()) // Doesn't work... .body("age", isNotPresent()); // ...But that's the idea. 我正在寻找一种方法来断言我的JSON是否会包含age和name您可以这样使用equals(null): .body(“姓氏”,
when()
.get("/person/12345")
.then()
.body("surname", isPresent()) // Doesn't work...
.body("age", isNotPresent()); // ...But that's the idea.
我正在寻找一种方法来断言我的JSON是否会包含age和name您可以这样使用equals(null):
.body(“姓氏”,等于(空))
如果该字段不存在,则该字段将为空检查字段是否为空。例如:
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();
您也可以在JSON字符串上使用Hamcrest匹配器(来自
org.Hamcrest.Matchers
class)
when()
.get("/person/12345")
.then()
.body("$", hasKey("surname"))
.body("$", not(hasKey("age")));
使用:
import static org.junit.Assert.assertThat代码>
你可以:
断言(response.then().body(包含字符串(“thinthattshouldtbehere”))为(false))
这也匹配设置为null的JSON字段。您是对的,但如果它接收到null,则基本上是相同的,因为如果未设置字段,则JavaScript客户端会将其视为未定义的,而不是null
。如果您尝试从XML提取数据,并检查它是否为空,这种方法行不通。正确的答案是:body($),not(hasKey(“user.age”))这是正确的答案,为什么不把它标记为一个呢?为了了解更多的知识,不需要点击更多的链接:hasKey()方法来自类org.hamcrest.Matchersif it,如果它是数组,您需要一个示例。body($),not(hasKey(数组[1]);如果是嵌套的json,它将无法工作?我猜上面表达式中的“$”将更改为类似“$.NameOfNode.AnotherNode”的描述性路径?