Reputation: 2053
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//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() {
}
}
Upvotes: 0
Views: 812
Reputation: 21113
If your GenericDAOImpl
is a simple wrapper around a Hibernate Session
and you're compelled to create tests for this implementation, then I would suggest creating a very basic entity and a respective implementation of your GenericDAOImpl
for said entity.
For example:
@Entity
public class BasicTestEntity {
@Id @GeneratedValue private Integer id;
private String name;
}
public class BasicTestEntityDao
extends GenericDaoImpl<BasicTestEntity, Integer> {
}
If you find you have certain situations where you need more explicit tests for this layer, simply add them and test them using mock/simple classes.
Nothing here needs to be tied with your actual real entities that you're using in higher levels of your code. That type of testing will surface with integration and unit tests for those specific modules and layers.
Upvotes: 1