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
You should use all significant variables, ie variables whose value is not derived from the others, in equals.
This is from Effective Java:
For each “significant” field in the class, check if that field of the argument matches the corresponding field of this object.
If you want to match ids because it's a unique identifier for that class then just compare the id value, don't use equals in that case.
If you have a unique identifier, the language doesn't allow you to enforce that there is no other object with that identifier or that the rest of variables' values match. However, you can define that in the documentation of the class and you can use assertions in the equals implementation or elsewhere as it is an invariant given by your class' semantics.