1

Given

List<Integer> list = ...

I would like to test with AssertJ whether it is sorted. Something like:

assertThat(list).isSorted()

Is it possible?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user3429660
  • 2,420
  • 4
  • 25
  • 41

2 Answers2

5

AssertJ offers out of the box isSorted() and isSortedAccordingTo(Comparator) for list assertions:

List<String> strings = List.of("abc", "DEF");

assertThat(strings).isSorted(); // fails as "abc" is after "DEF" lexicographically
assertThat(strings).isSortedAccordingTo(String.CASE_INSENSITIVE_ORDER); // succeeds
Stefano Cordio
  • 1,687
  • 10
  • 20
  • In case somebody else faces the same issue: I was testing `assertThat(CollectionObject).isSorted()`, which doesn't compile. I should have done something like: `assertThat(ListObject).isSorted()`. – user3429660 Mar 04 '22 at 20:01
0

import com.google.common.collect.Ordering;

And

assertTrue(Ordering.natural().isOrdered(list));