Search code examples
rest-assuredhamcrest

Rest assured response in ASC/DESC order


Is there any ways to validate the response in order?

"user": [
            {
                "_id": "1",
                "age": 21,             
            },
            {
                "_id": "2",
                "age": 22,
            },
            {
                "_id": "7",
                "age": 30,
            }
]

I can get specific id value with following

 .body("user[0].id", some validation)  result: 1

When I do something like this I will get all the ids

.body("user.id", some validation)  result: [1,2,7]

Need a validation to verify the result is in DESC/ASC order

.body("user.id", isDescOrder()/isAscOrder())

Solution

  • You can use isInOrder(Iterable<? extends T> iterable, Comparator<T> comparator) in com.google.common.collect.Comparators.

    List<String> user_IdList = given()
            .when()
            .get("api_url")
            .then()
            .extract()
            .jsonPath()
            .getList("user._id");
    
    List<Integer> integerList = user_IdList
            .stream()
            .map(x-> Integer.parseInt(x))
            .collect(Collectors.toList());
    
    boolean isInAscOrder = isInOrder(integerList, Ordering.natural());
    

    Here isInAscOrder will be true. Because 1,2,7 are in ascending order.