简体   繁体   English

JUNIT 如何检查检索到的自定义 object 在 assertthat 中排序

[英]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.嗨,我正在使用 Hibernate 以排序顺序 FindByOrderByValueAsc 检索元素。

How to check it is sorted in Junit?如何检查它是否在 Junit 中排序?

Presumably you have the retrieved elements in a List<SomeType> .大概您在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.编写一个方法,该方法将使用Comparator<T>迭代List<T> > 以比较连续元素,如果一对无序则返回 false。

Write the assertion to call the method on the retrieved elements with an appropriate Comparator<SomeType> .编写断言以使用适当的Comparator<SomeType>对检索到的元素调用方法。 Fail the assertion if the call returns false .如果调用返回false ,则断言失败。

create a Comparator for the fields that you are interested in.为您感兴趣的字段创建一个Comparator器。

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.有些断言库可以与 JUnit 一起使用,它们具有比 JUnit 本身更复杂的断言。 Eg with AssertJ you can write例如,您可以使用AssertJ编写

assertThat(theList).containsExactly(firstValue, secondValue)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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