AssertJ:断言列表是否按倒序或降序排序
AssertJ: Assert if list is sorted inversely or in descending order
我正在使用 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",
....]>
是的。还有方法 isSortedAccordingTo
which takes a Comparator
.
您需要将通用类型参数更改为 <T extends Comparable<T>>
,即具有自然顺序的类型。然后 Comparator.reverseOrder()
可以用来断言它应该是其自然顺序 的相反 。如果没有该约束,您将尝试颠倒某些 unknown/unspecified 顺序,这会导致编译器错误。
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;
}
}
我正在使用 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",
....]>
是的。还有方法 isSortedAccordingTo
which takes a Comparator
.
您需要将通用类型参数更改为 <T extends Comparable<T>>
,即具有自然顺序的类型。然后 Comparator.reverseOrder()
可以用来断言它应该是其自然顺序 的相反 。如果没有该约束,您将尝试颠倒某些 unknown/unspecified 顺序,这会导致编译器错误。
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;
}
}