Automagic unit tests for upholding Object method contracts in Java?

前端 未结 8 1364
傲寒
傲寒 2021-01-04 14:11

When developing Java applications, I often override Object methods (usually equals and hashCode). I would like some way to systematically check that I\'m adhering to the co

相关标签:
8条回答
  • 2021-01-04 15:02

    I have a first rough implementation, for equals testing with Constructor using only primitive parameters here. Just copy-paste it in test.MyClass.java file and run it.

    Warning: 1720 lines of code (0 errors in findbugs, 0 in "modified" checkstyle, cyclomatic complexity under 10 for all functions).

    See all the code at: Auto-test for equals function in java classes through annotations

    0 讨论(0)
  • 2021-01-04 15:05

    New answer for an old question, but in May of 2011 Guava (formerly Google Collections) released a class that removes a lot of the boilerplate, called EqualsTester. You still have to create your own instances but it takes care of comparing each object to itself, to null, to every object in the equality group, to every object in every other equality group, and to a secret instance that should match nothing. It also checks that a.equals(b) implies a.hashCode() == b.hashCode() across all those combinations.

    Example from Javadoc:

    new EqualsTester()
       .addEqualityGroup("hello", "h" + "ello")
       .addEqualityGroup("world", "wor" + "ld")
       .addEqualityGroup(2, 1 + 1)
       .testEquals();
    
    0 讨论(0)
提交回复
热议问题