Reputation: 43
Hi I am using Hibernate to retreive the element in sorted order FindByOrderByValueAsc.
How to check it is sorted in Junit?
Upvotes: 1
Views: 54
Reputation: 24520
There are assertion libraries that can be used with JUnit that have more sophisticated assertions than JUnit itself. E.g. with AssertJ you can write
assertThat(theList).containsExactly(firstValue, secondValue)
Upvotes: 1
Reputation: 120868
create a Comparator
for the fields that you are interested in.
Comparator<YourObject> cmp =
Comparator.comparing(YourObject::getOrder)
.thenComparing(YourObject::getValue);
for(int i = 0; i < yourResult.size() - 1; ++i) {
YourObject left = yourResult.get(i);
YourObject right = yourResult.get(i + 1);
if(cmp.compare(left, right) > 0) {
Assert.fail("not sorted")
}
}
have not compiled, obviously, any of this code.
Upvotes: 1
Reputation: 718946
Presumably you have the retrieved elements in a List<SomeType>
.
Write a method that will iterate a List<T>
using a Comparator<T>
to compare successive elements, and return false if a pair is out of order.
Write the assertion to call the method on the retrieved elements with an appropriate Comparator<SomeType>
. Fail the assertion if the call returns false
.
Upvotes: 1