Assert集合包含自定义类的对象,它不会覆盖equals/hashcode

ham*_*est 6 java collections junit equals hamcrest

我们有一个包含多个字段的自定义类,由于业务域原因,我们无法覆盖equals/hashcode方法

然而,在单元测试期间,我们应断言集合是否包含此类的项目

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
Run Code Online (Sandbox Code Playgroud)

但是,到目前为止,我们没有找到任何可以在不覆盖equals/hashcode的情况下工作的解决方案,例如Hamcrest

assertThat(customObjectList, contains(customObject));
Run Code Online (Sandbox Code Playgroud)

导致AssertionError引用

Expected: iterable containing [<CustomClass@578486a3>]
but: item 0: was <CustomClass@551aa95a>
Run Code Online (Sandbox Code Playgroud)

是否有解决方案,而无需逐场比较?

ham*_*est 4

我想说谢谢您的所有回复,其中提出了一些非常好的观点

但是,我在问题中忘记提及的是,我们的自定义类是递归的,即包含其他自定义类类型的字段,对于这些字段,对于 equals 和 hashcode 覆盖适用相同的限制。不幸的是,提到的开箱即用解决方案(AssertJ、Nitor Creations)似乎都不支持深度比较

尽管如此,似乎仍然有一个解决方案,那就是 Unitils 中的 ReflectionAssert 类。以下似乎按我们的预期工作,甚至能够忽略集合中的元素顺序

assertReflectionEquals(Arrays.asList(customObject1, customObject3, customObject2), customObjectList, ReflectionComparatorMode.LENIENT_ORDER);
Run Code Online (Sandbox Code Playgroud)