Automagic unit tests for upholding Object method contracts in Java?

前端 未结 8 1365
傲寒
傲寒 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 14:44

        public static void checkObjectIdentity(Object a1, Object a2, Object b1) {
            assertEquals(a1, a2);
            assertEquals(a2, a1);
            assertNotSame(a1, a2);
            assertEquals(a1.hashCode(), a2.hashCode());
            assertFalse(a1.equals(b1));
            assertFalse(a2.equals(b1));
            assertFalse(b1.equals(a1));
            assertFalse(b1.equals(a2));
        }
    

    Usage:

            checkObjectIdentity(new Integer(3), new Integer(3), new Integer(4));
    

    Can't think of anything better. Add new calls to checkObjectIdentity when you find a bug.

提交回复
热议问题