用Java维护对象方法契约的自动单元测试? [英] Automagic unit tests for upholding Object method contracts in Java?

查看:90
本文介绍了用Java维护对象方法契约的自动单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在开发Java应用程序时,我经常重写Object方法(通常是equals和hashCode)。我想通过某种方式系统地检查我是否遵守每个类的Object方法的合同。例如,我想要测试断言对于相等的对象,哈希码也是相等的。我正在使用JUnit测试框架,所以最好我想要一些JUnit解决方案,我可以自动生成这些测试,或者一些测试用例可以以某种方式访问​​我的所有类,并确保合同得到维护。

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 contract for Object methods for every one of my classes. For example, I want tests that assert that for equal objects, the hash code is also equal. I'm using the JUnit test framework, so preferably I'd like some JUnit solution where I can automatically generate these tests, or some test case that can somehow visit all of my classes and make sure that the contract is upheld.

我正在使用JDK6和JUnit 4.4。

I'm using JDK6 and 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));

想不出更好的事情。当您发现错误时,添加对checkObjectIdentity的新调用。

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

这篇关于用Java维护对象方法契约的自动单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆