JUnit theory for hashCode/equals contract

前端 未结 5 1266
情深已故
情深已故 2020-12-07 19:05

The following class serve as generic tester for equals/hashCode contract. It is a part of a home grown testing framework.

  • What do you think about?
  • Ho
相关标签:
5条回答
  • 2020-12-07 19:42

    Maybe I'm missing something, but the equalsIsSymmetric test is in fact only correctly tested if you have to DataPoints which have the same values (e.g. String a = "a"; String a2 = "a";) Otherwise this test is only done when the 2 parameters are one instance (i.e. equalsIsSymmetric(a, a);). In fact you test again if equals obey the 'reflective' requirement instead of the symmetric requirement.

    0 讨论(0)
  • 2020-12-07 19:42

    The notEqualsWorks(Object x, Object y) theory is false: two distinct instances may still be logically equal according to their equals method; you're assuming instances are logically different if they're different references.

    Using your own example above, the two distinct datapoints below (a != a2) are nevertheless equal but fail the notEqualsWorks test:

    @DataPoint
    public static String a = "a";
    @DataPoint
    public static String a2 = new String("a");
    
    0 讨论(0)
  • 2020-12-07 19:48

    One thing to consider: testing an object's conformance to the equals contract should involve instances of other types. In particular, problems are likely to appear with instances of a subclass or superclass. Joshua Bloch gives an excellent explanation of the related pitfalls in Effective Java (I'm reusing duffymo's link, so he should get credit for it) -- see the section under Transitivity involving the Point and ColorPoint classes.

    True, your implementation doesn't prevent someone from writing a test that involves instances of a subclass, but because ObjectTest is a generic class it gives the impression that all data points should come from a single class (the class being tested). It might be better to remove the type parameter altogether. Just food for thought.

    0 讨论(0)
  • 2020-12-07 20:03

    The equalsWorks(Object x, Object y) method is doing the very same test as equalsIsReflexive(Object x). It should be removed.

    I also think that notEqualsWorks(Object x, Object y) should be removed since it prevents one to do the other theories with data points that are equal even thought the whole testing is about having such objects.

    Without such data points the reflexivity is the only thing that is tested.

    0 讨论(0)
  • 2020-12-07 20:05

    Joshua Bloch lays out the contract for hash code and equals in chapter 3 of "Effective Java". Looks like you covered a great deal of it. Check the document to see if I missed anything.

    0 讨论(0)
提交回复
热议问题