您可以使用hamcrest-more-matchers(在Maven Central上可用)。它有两种实用方法来验证已排序的集合:(softOrdered
允许相等的顺序项)和strictOrdered
(不允许相等的项)。使用示例:
import com.github.seregamorph.hamcrest.OrderMatchers.*;
@Test
public void softOrderedEqualShouldSuccess() {
// success
assertThat(Arrays.asList(1, 1, 2), softOrdered());
// fails with diagnostics
// java.lang.AssertionError:
// Expected: Strictly ordered by natural comparator
// but: Found equal elements 1 and 1
assertThat(Arrays.asList(1, 1, 2), strictOrdered());
}
或者可以嵌套:
@Test
public void nestedCollectionShouldMatchOrderedItem() {
List<Iterable<Integer>> nested = Arrays.asList(
Arrays.asList(3, 2, 1),
Arrays.asList(1, 2, 3)
);
// success
assertThat(nested, hasItem(strictOrdered()));
// fails with diagnostics
// java.lang.AssertionError:
// Expected: every item is Softly ordered by natural comparator
// but: an item Found unordered elements 3 and 2
assertThat(nested, everyItem(softOrdered()));
}
默认情况下使用自然比较器,但也可以自定义:
import static java.util.Comparator.comparing;
@Test
public void stringsShouldMatchOrderByLength() {
List<String> list = Arrays.asList("abc", "ab", "a");
assertThat(list, strictOrdered(comparing(String::length).reversed()));
}