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

jul*_*ano 19 java rest rest-assured

我怎样才能确保我的响应(包括它是JSON)包含不包含特定字段?

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

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

Luc*_*ens 43

您也可以在JSON字符串上使用Hamcrest匹配器hasKey().

when()
    .get("/person/12345")
.then()
    .body("$", hasKey("surname"))
    .body("$", not(hasKey("age")));
Run Code Online (Sandbox Code Playgroud)

  • 这是正确答案,为什么不将其标记为一个? (8认同)
  • 无需单击其他链接即可获得知识:hasKey()方法来自类org.hamcrest.Matchers (2认同)

小智 0

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

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

如果该字段不存在则为空

  • 这也匹配设置为 null 的 JSON 字段。 (6认同)