AssertJ: Assert if list is sorted inversely or in descending order
Asked Answered
P

2

15

I'm using AssertJ for my tests and I noticed there's a method for checking if a List<T> is sorted:

public static <T> void sorted(final List<T> actual) {
    try {
        assertThat(actual).isSorted();
    } catch (AssertionError e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    }
}

Is there a way to check if the list is sorted in descending order?

I know guava provides Ordering.natural().reverse().isOrdered(values) but I want to take advantage of AssertJ's assert messages as it really helps a lot in debugging e.g.

group is not sorted because element 5:
 <"4000366190001391">
is not less or equal than element 6:
 <"4000206280001394">
group was:
 <["4000206280001363",
    "4000206280001364",
    "4000206280001365",
    "4000206280001373",
    "4000206280001388",
    "4000366190001391",
    "4000206280001394",
    "4000366190001401",
    "4000206280001403",
    "4000206280001405",
     ....]>
Pandanus answered 13/12, 2017 at 11:46 Comment(0)
R
20

Yes. There's also the method isSortedAccordingTo which takes a Comparator.

You'll need to change the generic type parameter to <T extends Comparable<T>>, i.e. a type which has a natural ordering. Then Comparator.reverseOrder() can say be used to assert that it should be the reverse of it's natural ordering. Without that constraint, you'd be trying to reverse some unknown/unspecified ordering, which results in a compiler error.

public static <T extends Comparable<T>> void sorted(final List<T> actual) {
    try {
        assertThat(actual).isSortedAccordingTo(Comparator.reverseOrder());
    } catch (AssertionError e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    }
}
Rosemari answered 13/12, 2017 at 11:58 Comment(0)
O
1
assertThat(downloadHistory).extracting("downloadedAt", LocalDateTime.class)
                .isSortedAccordingTo(Comparator.reverseOrder());
Ola answered 15/3, 2023 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.