Alex Rivera | Logout

Automagic unit tests for upholding Object method contracts in Java?

Asked 2008-10-10T03:22:10.570
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 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.

I'm using JDK6 and JUnit 4.4.

Edit
Report

3 Answers

2
    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.

answered 2008-10-10T12:08:58.700
0

This problem doesn't have "easy" solution unless you're putting strong constraints on your classes.

For example, if you're using several constructors for a given class, how can you ensure that all your parameters are well taken into account in your equals/hash methods? How about defaults values? These are things that, unfortunately, cannot be automated blindly.

answered 2008-10-10T06:02:21.727
0

I have a first rough implementation, for equals testing with Constructor using only primitive parameters here. Just copy-paste it in test.MyClass.java file and run it.

Warning: 1720 lines of code (0 errors in findbugs, 0 in "modified" checkstyle, cyclomatic complexity under 10 for all functions).

See all the code at: Auto-test for equals function in java classes through annotations

answered 2008-10-19T15:08:45.040

Your Answer