Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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",
     ....]>
like image 837
iamkenos Avatar asked Dec 13 '17 11:12

iamkenos


1 Answers

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;
    }
}
like image 84
Michael Avatar answered Oct 25 '22 17:10

Michael