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?
If you are using Java8 you could use Stream#anyMatch and your own customEquals method. Something like this would work -
assertTrue(customObjectList.stream()
.anyMatch(object -> customEquals(object,customObject)));
UPDATED to reflect Holger's comment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With