2016-06-10 127 views
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() { 

} 

} 

回答

1

如果您GenericDAOImpl是围绕一个Hibernate Session一个简单的包装,你就不得不为这个实现创建测试的话,我建议建立一个非常基本的实体和所述实体各自实现你的GenericDAOImpl的。

例如:

@Entity 
public class BasicTestEntity { 
    @Id @GeneratedValue private Integer id; 
    private String name; 
} 

public class BasicTestEntityDao 
    extends GenericDaoImpl<BasicTestEntity, Integer> { 
} 

如果你发现自己有某些情况下,你需要为这个层更明确的测试,只需添加它们,使用模拟/简单的类测试它们。

这里没有什么需要与您在代码的更高级别中使用的实际实体绑定在一起。这种类型的测试将对这些特定模块和层进行集成和单元测试。

+0

也许这是最好的解决方案。谢谢! – angeldev