简体   繁体   中英

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?

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 .

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.

There are assertion libraries that can be used with JUnit that have more sophisticated assertions than JUnit itself. Eg with AssertJ you can write

assertThat(theList).containsExactly(firstValue, secondValue)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM