We have a custom class with several fields, for which we cannot override equals/hashcode methods for business domain reasons
Nevertheless, during unit testing we should assert on whether a collection contains an item of this class
List<CustomClass> customObjectList = classUnderTest.methodUnderTest();
//create customObject with fields set to the very same values as one of the elements in customObjectList
//we should assert here that customObjectList contains customObject
However, so far we did not find any solution that would work without overriding equals/hashcode, e.g. Hamcrest
assertThat(customObjectList, contains(customObject));
results in AssertionError citing
Expected: iterable containing [<CustomClass@578486a3>]
but: item 0: was <CustomClass@551aa95a>
Is there a solution to this without having to compare field-by-field?
anyMatch
requires a predicate. Fixing that makes thefilter
obsolete:customObjectList.stream().anyMatch(object -> customEquals(object,customObject))
– Fornix