AssertJ:如果列表按逆序或降序排序,则断言

时间:2017-12-13 11:46:32

标签: java list sorting assertj

我正在使用AssertJ进行测试,我注意到有一种检查List<T>是否已排序的方法:

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

有没有办法检查列表是否按降序排序?

我知道guava提供Ordering.natural().reverse().isOrdered(values)但是我想利用AssertJ的断言消息,因为它在调试方面确实有很大帮助,例如。

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",
     ....]>

1 个答案:

答案 0 :(得分:5)

是。还有方法isSortedAccordingTo,它采用Comparator

您需要将通用类型参数更改为<T extends Comparable<T>>否则无法确定订单应该是什么。

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;
    }
}