Testing Interface Contracts

March 27th, 2006

Often when you define an interface there is a series of generic tests which can be applied to every implementation of that interface. For instance, the java.util.List interface carefully defines the behavior that all implementations must have. A simple way of testing these behaviors are present is to use JUnit's ability to inherit test methods.

Define a base class with a test method for what you want and an abstract method to create the actual instance:

public abstract class ListTestBase extends TestCase {
    public void testAdd() {
        List impl = createList();
        Object expected = new Object();
        impl.add(obj);
        assertSame(expected, impl.get(0));
    }

    protected abstract List createList();
}

Then simply extend ListTestBase when you write the tests for your list implementations and they will all inherit the testAdd method. This can be useful anytime you want to apply a common set of tests to multiple different classes.