vendredi 10 juin 2016

Best practise testing generic DAO

I have an abstract GenericDAO with common methods for all entities. I am using Spring and Hibernate the project. The source code of the GenericDAO is:

public abstract class GenericDAOImpl <T, PK extends Serializable> implements GenericDAO<T, PK> {

private SessionFactory sessionFactory;

/** Domain class the DAO instance will be responsible for */
private Class<T> type;

@SuppressWarnings("unchecked")
public GenericDAOImpl() {
    Type t = getClass().getGenericSuperclass();
    ParameterizedType pt = (ParameterizedType) t;
    type = (Class<T>) pt.getActualTypeArguments()[0];
}

@SuppressWarnings("unchecked")
public PK create(T o) {
    return (PK) getSession().save(o);
}

public T read(PK id) {
    return (T) getSession().get(type, id);
}

public void update(T o) {
    getSession().update(o);
}

public void delete(T o) {
    getSession().delete(o);
}

I have created a genericDAOTest class to test this generic methods and don't have to repeat them in each test case of different entities, but I don't find the way of do that. Is there any way of avoid to test this generic methods in each class? Thanks!

I am using DBUnit to test DAO classes. For testShouldSaveCorrectEntity I can't create a "Generic Entity" because each entity has not null fields which I have to set. So, I think it is impossible to do that.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/com/port80/sftp/spring/dao-app-ctx-test.xml")
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
    TransactionDbUnitTestExecutionListener.class})
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public abstract class GenericDAOTest<T, PK extends Serializable> {
protected GenericDAO<T, PK> genericDAO;

public abstract GenericDAO<T, PK> makeGenericDAO();

@Test
@SuppressWarnings("unchecked")
public void testShouldGetEntityWithPK1() {
    /* If in the future exists a class with a PK different than Long, 
    create a conditional depending on class type */
    Long pk = 1l;

    T entity = genericDAO.read((PK) pk);
    assertNotNull(entity);
}

@Test
public void testShouldSaveCorrectEntity() {

}

}

Aucun commentaire:

Enregistrer un commentaire