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

后端 未结 23 1667
臣服心动
臣服心动 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 06:06

    From your comments to other answers, I don't understand what you want.

    Just for the sake of discussion, lets say that the the class did override the equals method.

    So your UT will look something like:

    SomeType expected = // bla
    SomeType actual = // bli
    
    Assert.assertEquals(expected, actual). 
    

    And you are done. Moreover, you can not get the "full equality picture" if the assertion fails.

    From what I understand, you are saying that even if the type did override equals, you would not be interested in it, since you want to get the "full equality picture". So there is no point in extending and overriding equals either.

    So you have to options: either compare property by property, using reflection or hard-coded checks, I would suggest the latter. Or: compare human readable representations of these objects.

    For example, you can create a helper class that serializes the type you wish tocompare to an XML document and than compare the resulting XML! in this case, you can visually see what exactly is equal and what is not.

    This approach will give you the opportunity to look at the full picture but it is also relatively cumbersome (and a little error prone at first).

提交回复
热议问题