Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does `containsInAnyOrder` compare items?

I’ve got a CustomField class and I’ve overriden the equals and hashcode methods. But when I try to compare 2 lists of CustomField objects, it fails.
Why wouldn’t the containsInAnyOrder work in the following:

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Check this out: https://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(T…)

containsInAnyOrder expects an array of elements to match with the provided actual list.
You are passing expected as list. And actual is not a List of List.
So, it will try to search for an entire list as an element in actual.

Probably you will need to use containsInAnyOrder(expected.toArray()).

I.e.

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

Try it out.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading