`containsInAnyOrder`如何比较项目?

问题描述 投票:0回答:1

我有一个

CustomField
类,并且我已经重写了 equals 和 hashcode 方法。但是当我尝试比较 2 个
CustomField
对象列表时,它失败了。 为什么
containsInAnyOrder
不能用于以下情况:

Overrides:
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CustomField that = (CustomField) o;
        return Objects.equals(this.id, that.id) &&
                Objects.equals(this.name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.id, this.name);
    }

        List<CustomField> actual = ImmutableList.of(
                new CustomField(1L, "1L"),
                new CustomField(2L, "2L"),
                new CustomField(3L, "3L")
        );
        List<CustomField> expected = ImmutableList.of(
                new CustomField(1L, "1L"),
                new CustomField(2L, "2L"),
                new CustomField(3L, "3L")
        );
        assertThat(actual, containsInAnyOrder(expected)); /// why does this fail?
java testing contains assert hamcrest
1个回答
2
投票

检查一下:https://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(T...)

containsInAnyOrder
期望元素数组与提供的
actual
列表匹配。 您正在将
expected
作为列表传递。并且
actual
不是列表的列表。 因此,它将尝试将整个列表作为
actual
中的元素进行搜索。

可能您需要使用

containsInAnyOrder(expected.toArray())

assertThat(actual, containsInAnyOrder(expected.toArray()));

尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.