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?
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.