Reputation: 403
I'm trying to validate some properties of my response as shown in the rest assured tutorial.
The problem is that, when testing properties inside an array, I can verify, as in the example, that they appear, but not that they're matched to other properties of the element as they should.
To clarify, let's say I have the response from the tutorial (added "prize")
{
"lotto":{
"lottoId":5,
"winning-numbers":[2,45,34,23,7,5,3],
"winners":[{
"winnerId":23,
"prize":5000,
"numbers":[2,45,34,23,3,5]
},{
"winnerId":54,
"prize":100000,
"numbers":[52,3,12,11,18,22]
}]
}
}
I can validate that the winnerIds as 23, and 54
expect().
body("lotto.lottoId", equalTo(5)).
body("lotto.winners.winnderId", hasItems(23, 54)).
when().
get("/lotto");
and I could validate that the prizes are 500 and 100000, but I can't validate that the winnerId=23 has a prize=500 and the winnerId=54 a prize=100000. The response would show the winnerId=23 with a prize=100000 and the tests would pass.
I can't use contains() because the elements in the array can come in any order, so I need to user containsInAnyOrder().
Upvotes: 5
Views: 7824
Reputation: 3755
Using hamcrest, note to take, one item in the winners list is considered as a map.
@Test
void test() {
expect()
.body("lotto.lottoId", equalTo(5))
.body("lotto.winners.", allOf(
hasWinner(23, 5000),
hasWinner(54, 100000)
))
.when()
.get("/lotto");
}
private Matcher<Iterable<? super Map<? extends String, ? extends Integer>>> hasWinner(int winnerId, int prize) {
return hasItem(allOf(
hasEntry(equalTo("winnerId"), equalTo(winnerId)),
hasEntry(equalTo("prize"), equalTo(prize))
));
}
Upvotes: 2
Reputation: 4666
As far as I know, Rest-Assured only allows to verify straight forward value verification. For conditional verification, you have to use jsonpath instead:
$.lotto.winners.[?(@.winnerId==23)].prize
Above jsonpath searches for winners
array under lotto
and selects the array item which has winnerId==23
and then retrieves the prize;
expect().
body("$.lotto.winners.[?(@.winnerId==23)].prize", equalTo(5000)).
when().
get("/lotto");
There are other posts in SO that you can referenc are here and here
Try the expression in this link
JsonPath expression syntax can be found here.
Upvotes: 4