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",
....]>
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With