Alex Rivera | Logout

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

Asked 2011-01-18T21:02:06.720
18

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?

Edit
Report

1 Answer

1

If using a different entity type causes different code to execute, then you need a separate test case.

I'd test as much as I could in a common set of tests that only use one entity type. If most of your code treats all entities the same, then there's no need to test it more than once. I'd set up separate test cases for any special behavior that's required where specific entity DAOs have different behavior.

answered 2011-01-18T21:17:43.467

Your Answer