简体   繁体   English

使用 hamcrest 检查列表是否包含特定顺序的类实例

[英]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.

相关问题 如何使用 Hamcrest 检查集合是否包含按给定顺序的项目 - How to check if collection contains items in given order using Hamcrest Java Hamcrest Matcher 检查列表是否包含另一个列表 - Java Hamcrest Matcher check if list contains another list Hamcrest Matchers包含匹配列表 - Hamcrest Matchers contains with List of matchers assertThat - hamcrest - 检查列表是否已排序 - assertThat - hamcrest - check if list is sorted 检查日期列表是否包含特定日期 - Check if a list of dates contains a particular date 使用hamcrest contains()方法比较两个集合 - Comparing two collections using hamcrest contains() method 如何检查List是否按顺序包含多个元素 - How to check if List contains several elements in order 如何使用Struts 2检查List是否包含特定元素为null <s:if> 标签? - How to check List contains the particular element null or not in Struts 2 using <s:if> Tags? 如何使用AssertJ检查某些List是否仅包含一个特定元素或为空 - How to check if some List contains only one particular element OR is empty using AssertJ 使用 REST 和 Java Hamcrest 检查数组是否包含具有多个键值对的项目,其中值具有不同的类型 - Using REST assured with Java Hamcrest to check if Array contains item with multiple key value pairs where the values have a different type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM