What unit test to write for a class using generics in Java?

Sébastien Le Callonnec picture Sébastien Le Callonnec · Jan 18, 2011 · Viewed 9.1k times · Source

Taking the very specific example of the JpaDao class defined in this article:

public abstract class JpaDao<K, E> implements Dao<K, E> {
    protected Class<E> entityClass;

    @PersistenceContext
    protected EntityManager entityManager;

    public JpaDao() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[1];
    }

    public void persist(E entity) { entityManager.persist(entity); }

    public void remove(E entity) { entityManager.remove(entity); }

    public E findById(K id) { return entityManager.find(entityClass, id); }
}

would it be best to write unit tests for all the existing entities in the application (Order, Customer, Book, etc.), or would it be acceptable to write unit tests for just one entity, as hinted by this other question? Are there any best practice regarding unit testing java classes using generics?

Answer

Marty Pitt picture Marty Pitt · Jan 18, 2011

You could write an abstract test class for entities which subclass this.

Eg:

public abstract class JpaDaoTest<K,E> {

    abstract protected E getEntity();
    abstract protected JpaDao getDAO();

    @Test
    public void testPersistCreatesEntity()
    {
         JpaDao dao = getDAO();
         dao.persist(getEntity());
         // assert
     }
}

The contract you generic classes implement should be able to be tested just as genericlly, assuming that getEntity() sets up and relational dependencies correctly.

Therefore, by subclassing this test class for all the test cases for your generic subclasses, you get the tests for free.