3

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?

JustNatural
  • 375
  • 7
  • 19

1 Answers1

6

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

bhusak
  • 1,320
  • 1
  • 9
  • 19