How do I match items in a list from an anonymous root from a RestAssured body?

433 Views Asked by At

I have this output

[
  {"name": "a"},
  {"name": "b"}
]

And the following code

given()
.get("endpoint")
.then()
.body("$.name", hasItem("b"));

But I get this result

java.lang.AssertionError: 1 expectation failed.
    JSON path $.name doesn't match.
    Expected: (a collection containing "b")
        Actual: <[]>

I've tried everything I can think of for path. I'm sure it's something dumb but what am I missing?

1

There are 1 best solutions below

0
On

Based on your JSON output, it appears that your JSON is an array of objects, with each object having a "name" property. So when you use the JSON path "$.name", it will try to find the "name" property at the top level of the JSON, which doesn't exist. Instead, you'll need to specify the array index to access the "name" property of the correct object.

You can try

.body("[1].name", hasItem("b")); 

to correctly access the name property of the 2nd object in the array: