在开发
Java应用程序时,我经常会重写Object方法(通常是equals和hashCode).我想要一些方法来系统地检查我是否遵守我每个课程的Object方法的合同.例如,我想要测试证明对于相等的对象,哈希码也是相等的.我使用JUnit测试框架,所以最好我想要一些JUnit解决方案,我可以自动生成这些测试,或者一些测试用例,可以访问我的所有课程,并确保合同得到维护.
我使用JDK6和JUnit 4.4.
解决方法
- 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));
- }
用法:
- checkObjectIdentity(new Integer(3),new Integer(3),new Integer(4));