【问题标题】:check if a List Contains instances of classes in a particular order using hamcrest使用hamcrest检查列表是否包含特定顺序的类实例
【发布时间】:2019-03-14 16:44:28
【问题描述】:

您好,我正在编写一个单元测试,我需要断言一个列表以特定顺序包含多个类的对象。我想使用 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 匹配器来实现这一点?

【问题讨论】:

  • 您使用的是哪个版本? 1.3 版似乎对我有用。

标签: java unit-testing junit assert hamcrest


【解决方案1】:

使用this method

public static <E> Matcher<java.lang.Iterable<? extends E>> containsInRelativeOrder(Matcher<? super E>... itemMatchers)

来自文档:

为 Iterables 创建一个匹配器,当单次通过检查的 Iterable 产生一系列项目时匹配,每个项目都以相同的相对顺序满足指定匹配器中的相应匹配器。例如: 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 起可用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2021-07-02
    • 2016-07-26
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多