Using REST Assured, how can I check if a field is present or not in an array of json objects type of response?

江枫思渺然 提交于 2020-02-24 11:08:08

问题


I need to validate that a response like the one below contains some fields. I am not interested in the fields value - just that the keys exist. For example I want to check that the key "id" is present in this type of response. How would I accomplish that?

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

If I do

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

I get an error like this:

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}]

Please, can someone explain to me how this should work?


回答1:


Try this:

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

Groovy GPath is used in Rest Assured. You can take a look at their guide here

Also there's a good tutorial here



来源:https://stackoverflow.com/questions/54089850/using-rest-assured-how-can-i-check-if-a-field-is-present-or-not-in-an-array-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!