5

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().

user384729
  • 403
  • 1
  • 7
  • 16

2 Answers2

4

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.

Community
  • 1
  • 1
parishodak
  • 4,506
  • 4
  • 34
  • 48
2

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))
    ));
}
Ruwanka De Silva
  • 3,555
  • 6
  • 35
  • 51