[英]check if a List Contains instances of classes in a particular order using hamcrest
Hi I am writing a unit test where I need to assert that a list contains objects of multiple classes in a specific order.嗨,我正在编写一个单元测试,我需要在其中断言列表包含按特定顺序包含多个类的对象。 I want to do this using hamcrest.我想使用 hamcrest 来做到这一点。
Right now I am asserting it like -现在我断言它就像 -
assertThat(actual, hasItem(isA(A.class)));
assertThat(actual, hasItem(isA(B.class)));
assertThat(actual, hasItem(isA(C.class)));
Here I want to test that the items are in order A->B->C.这里我想测试一下,物品的顺序是A->B->C。 I have tried writing it like -我试过把它写成 -
assertThat(actual, contains(isA(A.class), isA(B.class), isA(C.class)));
but this is not supported, is there a way to achieve this with hamcrest matchers?但这不受支持,有没有办法用 hamcrest 匹配器来实现这一点?
Use this method :使用此方法:
public static <E> Matcher<java.lang.Iterable<? extends E>> containsInRelativeOrder(Matcher<? super E>... itemMatchers)
From the docs:从文档:
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.为 Iterable 创建一个匹配器,当单次通过检查的 Iterable 产生一系列项目时匹配,每个项目都满足指定匹配器中的相应匹配器,以相同的相对顺序。 For example: assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))例如: assertThat(Arrays.asList("a", "b", "c", "d", "e"), containsInRelativeOrder(equalTo("b"), equalTo("d")))
In your case, it could be like this:在你的情况下,它可能是这样的:
assertThat(actual, containsInRelativeOrder(isA(A.class), isA(B.class), isA(C.class)));
Available since Hamcrest 2.0.0.0.从 Hamcrest 2.0.0.0 开始可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.