Automagic unit tests for upholding Object method contracts in Java?

前端 未结 8 1406
傲寒
傲寒 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: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();
    

提交回复
热议问题