How do I assert equality on two classes without an equals method?

后端 未结 23 1555
臣服心动
臣服心动 2020-11-28 05:20

Say I have a class with no equals() method, to which do not have the source. I want to assert equality on two instances of that class.

I can do multiple asserts:

23条回答
  •  醉梦人生
    2020-11-28 05:59

    I stumbled on a very similar case.

    I wanted to compare on a test that an object had the same attribute values as another one, but methods like is(), refEq(), etc wouldn't work for reasons like my object having a null value in its id attribute.

    So this was the solution I found (well, a coworker found):

    import static org.apache.commons.lang.builder.CompareToBuilder.reflectionCompare;
    
    assertThat(reflectionCompare(expectedObject, actualObject, new String[]{"fields","to","be","excluded"}), is(0));
    

    If the value obtained from reflectionCompare is 0, it means they are equal. If it is -1 or 1, they differ on some attribute.

提交回复
热议问题