Mocktheduck
Mocktheduck

Reputation: 1423

How to use Guava MapInterfaceTest to test your class

I'm trying to test a class that I've written and which implements the Map from Java using Guava-testlib MapInterfaceTest. When I try and run my MapTest which implements MapInterfaceTest, all the tests fail (almost, 52/56) even though all I did was to call the functions from LinkedHashMap.

Why is this happening? How does the guava interface test actually work and how can I fix my code? The debugger doesn't really help here.

For example, I have:

public void testEqualsForEmptyMap() {
        final Map<K, V> map;
        try {
            map = makeEmptyMap();
        } catch (UnsupportedOperationException e) {
            return;
        }

        assertEquals(map, map);
        assertEquals(makeEmptyMap(), map);
        assertEquals(Collections.emptyMap(), map);
        assertFalse(map.equals(Collections.emptySet()));
        //noinspection ObjectEqualsNull
        assertFalse(map.equals(null));
    }

My makeEmptyMap method:

@Override
    protected Map<Integer, String> makeEmptyMap() throws UnsupportedOperationException {
        return new MyMap<Integer, String>();
    }

My map:

private final HashMap<K, V> entries;

public MyMap() {
    entries = new LinkedHashMap<K, V>();
}

This test fails here: assertEquals(makeEmptyMap(), map);

Upvotes: 2

Views: 88

Answers (1)

Riduidel
Riduidel

Reputation: 22300

Considering the code visible in your MyMap class, the failure is quite normal : as you didn't override the Object#equals method, you use the default implementation, which relies upon in-memory equality of references (Object#equals is implemented using ==).

As a consequence, the JVM tries to check if both objects are the same instance in memory, which they aren't. And your test fails.

On a more general note, you have to implement the full interface of Map using, sometimes, non trivial code. So unless you exactly known what you do, and why you do it, prefer reusing existing Map implementation.

Upvotes: 3

Related Questions