isSorted() method doesn't work for list of String
vk765 opened this issue · comments
Please help me to understand why sort assertion doesn't work.
Code sample:
public static void main(String[] args) { List<String> res = Arrays.asList("framike","NataschaHuber","NataschaHuber","NataschaHuber","NataschaHuber","smolnikk"); assertThat(res).as("Sorting by username, order ASC").isSorted(); }
Result:
Exception in thread "main" java.lang.AssertionError: [Sorting by username, order ASC] group is not sorted because element 0: <"framike"> is not less or equal than element 1: <"NataschaHuber"> group was: <["framike", "NataschaHuber", "NataschaHuber", "NataschaHuber", "NataschaHuber", "smolnikk"]>
because this assertion checks if the given list is sorted, it does not sort it.
In the future, I would suggest to:
- consult the javadoc
- open issues in the correct project (assertj-core not the doc project)
Hope it helps
@joel-costigliola
So, I have already sorted list: "framike","NataschaHuber","NataschaHuber","NataschaHuber","NataschaHuber","smolnikk"
f -> N -> N -> N -> N-> s
Why assertion was failed? I meant that assertion failed even my list is sorted by String value. Not that your method doesn't sort
I found the reason. It's because I have upper and lowercase. But is it correct behaviour that I should set all values to lowercase if I wanna check the list is sorted?
As mentioned by isSorted()
javadoc:
Verifies that the actual list is sorted in ascending order according to the natural ordering of its elements.
The natural ordering of string elements is described in compareTo()
javadoc of java.lang.String
:
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.
If you want to have case-insensitive comparison, you should use String.CASE_INSENSITIVE_ORDER
as element comparator:
List<String> res = Arrays.asList("framike", "NataschaHuber", "NataschaHuber", "NataschaHuber", "NataschaHuber", "smolnikk");
assertThat(res).usingElementComparator(String.CASE_INSENSITIVE_ORDER)
.isSorted(); // succeeds
assertThat(res).isSorted(); // fails
Great, thanks