嗨,我正在编写一个单元测试,我需要断言列表包含按特定顺序的多个类的对象。我想用 hamcrest 来做到这一点。
现在我断言它就像 -
assertThat(actual, hasItem(isA(A.class)));
assertThat(actual, hasItem(isA(B.class)));
assertThat(actual, hasItem(isA(C.class)));
这里我想测试一下项目的顺序是A->B->C。我试过这样写 -
assertThat(actual, contains(isA(A.class), isA(B.class), isA(C.class)));
但这不受支持,有没有办法用 hamcrest 匹配器实现这一点?
最佳答案
使用this method :
public static <E> Matcher<java.lang.Iterable<? extends E>> containsInRelativeOrder(Matcher<? super E>... itemMatchers)
来自文档:
Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, that each satisfying the corresponding matcher in the specified matchers, in the same relative order. For example: assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))
就您而言,可能是这样的:
assertThat(actual, containsInRelativeOrder(isA(A.class), isA(B.class), isA(C.class)));
自 Hamcrest 2.0.0.0 起可用。
关于java - 使用 hamcrest 检查列表是否包含特定顺序的类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167914/