Best practice to choose fields for equals() implementation

前端 未结 5 1963
栀梦
栀梦 2021-02-05 13:43

When writing unit-tests, I often face the situation when equals() for some object in tests -- in assertEquals -- should work differently from how it wo

5条回答
  •  太阳男子
    2021-02-05 14:06

    Copied from Object.equals(Object obj) javadoc:

    Indicates whether some other object is "equal to" this one.

    The equals method implements an equivalence relation on non-null object references:

    • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
    • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
    • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
    • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
    • For any non-null reference value x, x.equals(null) should return false.

    That's pretty clear to me, that is how equals should work. As for which fields to choose, you choose whichever combination of fields is required to determine whether some other object is "equal to" this one.

    As for your specific case, if you, in your test, need a broader scope for equality, then you implement that in your test. You shouldn't hack your equals method just to make it fit.

提交回复
热议问题