0
我有一个抽象的GenericDAO,它具有所有实体的通用方法。我正在使用Spring和Hibernate这个项目。该GenericDAO的源代码是:测试通用DAO的最佳实践
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);
}
我创建了一个genericDAOTest类来测试这个通用的方法和不必重复它们在不同实体的每个测试案例,但我没有找到路做到这一点。有没有什么方法可以避免在每个类中测试这种通用方法?谢谢!
我正在使用DBUnit来测试DAO类。对于testShouldSaveCorrectEntity
我无法创建“通用实体”,因为每个实体都没有空字段,我必须设置。所以,我认为这是不可能的。
@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() {
}
}
也许这是最好的解决方案。谢谢! – angeldev