【问题标题】:Using REST Assured, how can I check if a field is present or not in an array of json objects type of response?使用 REST Assured,如何检查响应类型的 json 对象数组中是否存在字段?
【发布时间】:2019-01-08 10:29:20
【问题描述】:

我需要验证像下面这样的响应是否包含一些字段。我对字段值不感兴趣 - 只是键存在。 例如,我想检查这种类型的响应中是否存在键“id”。我将如何做到这一点?

[  
   {  
      "id":"1",
      "title":"Title",
      "details":"details",
      "benefit":"Welcome",
      "expirationTimestamp":1549995900,
      "notice":"some text",     
   }
]

如果我这样做了

given()
  .spec(reqSpec).
when()
  .get().
then()
  .body("$", hasKey("id"));

我收到这样的错误:

java.lang.AssertionError: 1 expectation failed.
JSON path $ doesn't match.
Expected: map containing ["id"->ANYTHING]
  Actual: [{blabla=something, id=1, details=details, etc=etc}]

请问,有人可以向我解释一下这应该如何工作吗?

【问题讨论】:

    标签: json rest-assured jsonpath web-api-testing rest-assured-jsonpath


    【解决方案1】:

    试试这个:

    given()
      .spec(reqSpec).
    when()
      .get().
    then()
      .body("[0]", hasKey("id"));
    

    Groovy GPath 用于 Rest Assured。你可以看看他们的指南here

    还有一个很好的教程here

    【讨论】:

    • 太棒了!非常感谢!您是否也知道我如何检查响应是否仅返回数组中的一个 json 对象而不是 2 个或更多?
    • @JustNatural 试试这个 .body("$", hasSize(1))
    • 有没有我们可以检查多个字段的。如果我们有 50 个字段并且想要检查怎么办。
    猜你喜欢
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多