sathish kumar
sathish kumar

Reputation: 43

JUNIT How to check the custom object retrieved is sorted in assertthat

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

Answers (3)

Stefan Birkner
Stefan Birkner

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

Eugene
Eugene

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

Stephen C
Stephen C

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

Related Questions