33

I have an anonymous array in JSON returned from a service like:

[
  {"foo":1, "bar":2 , "baz":3 },
  {"foo":3, "bar":4 , "baz":5 }
]

How can I access the bar elements e.g. in

expect().body("$[*].bar", hasItems(2,4)) 

I tried a few possibilities that I found here and also on the JsonPath page by Stefan Gössner, but whatever I try I get exceptions. My issue seems to directly come from trying to access that list of items.

tom redfern
  • 30,562
  • 14
  • 91
  • 126
Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119

2 Answers2

46

Given that you have:

[
  {"foo":1, "bar":2 , "baz":3 },
  {"foo":3, "bar":4 , "baz":5 }
]

You can do the following in Rest Assured:

then().body("bar",hasItems(2,4)) 

or

expect().body("bar",hasItems(2,4)) 

if you're using the legacy API.

Johan
  • 37,479
  • 32
  • 149
  • 237
33

Johan's answer is correct, just for the sake of completeness: An alternative way to check the 'bar' elements with rest-assured would be

expect().
    body("[0].bar", equalTo(2)).
    body("[1].bar", equalTo(4));
Matthias
  • 447
  • 4
  • 8
  • 6
    Just be careful with this - the order of elements may not always be the same. – Nebril Feb 18 '15 at 09:41
  • That's right, that's the main reason for using "hasItems" in the first place - you use it in cases where you can't expect a specific (and fixed) order. – cslotty Oct 07 '15 at 09:51
  • This is correct but if order gets change, it will surely fail. – rohitkadam19 Mar 31 '16 at 10:22
  • maybe Hamcrest `containsInAnyOrder()` will help you... http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(T...) – Julien Jun 09 '21 at 08:09