Automagic unit tests for upholding Object method contracts in Java?

前端 未结 8 1411
傲寒
傲寒 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条回答
  •  旧时难觅i
    2021-01-04 14:54

    [community post here, no karma involved ;) ]

    Here is another code-challenge for you:

    One java class, implementing a JUnit test case, with a main method able to launch JUnit on itself!

    This class will also:

    • override hash() and equals()
    • define a few attributes (with primitive types)
    • define a default constructor but also some constructors with various combinations of parameters
    • define an annotation able to enumerate "interesting" values to pass to those constructor
    • annotate equals() with those "interesting" values

    The test method takes a class name parameter (here: it will be itself), check if the class with that name has an equals() overridden method with "interesting values" annotations.
    If it does, it will builds the appropriate instances (of itself) based on the annotations, and test equals()

    This is a self-contained test class, which defines a mechanism able to be generalized to any class with an annotated overridden equals() function.

    Please Use JDK6 and JUnit4.4

    That class should be copied-paste in the appropriate package of an empty java project... and just run ;)


    To add some more thought, in response to Nicolas (see comments):

    • yes the data needed for test are within the class candidate to be tested (that is, the one overriding equals and helping any 'automatic tester' to build appropriate instances)
    • I do not see that exactly as "testing logic", but as useful comments on what is supposed to do the equals (and incidentally as data to be exploited by the aforementioned tester ;) )

    Should annotations representing potential testing data never ever be in the class itself ?... Hey that could be a great question to ask :)

提交回复
热议问题