Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert collection contains object of custom class, which does not override equals/hashcode

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?

like image 206
hammerfest Avatar asked Sep 21 '15 15:09

hammerfest


1 Answers

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

like image 163
John McClean Avatar answered Nov 15 '22 11:11

John McClean