【发布时间】:2019-07-25 14:16:31
【问题描述】:
我有包含@Autowired 字段的通用抽象类 AbstractBaseEntityGenericDao。它工作得很好,直到我不得不为它编写一个单元测试,而不是在扩展它的类的所有测试中复制相同的代码。现在我在想...是否可以为此类编写单元/集成测试?
@Repository
@Transactional
public abstract class AbstractBaseEntityGenericDao<T extends BaseEntity> {
private Class<T> classInstance;
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public final void setClassInstance(Class<T> clasInstance) {
this.classInstance = clasInstance;
}
public void create(@NonNull T entity) {
Session session = sessionFactory.getCurrentSession();
session.save(entity);
}
public Optional<T> find(long id) {
Session session = sessionFactory.getCurrentSession();
return Optional.ofNullable(session.get(classInstance, id));
}
public void update(@NonNull T entity) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(entity);
}
public void remove(@NonNull Long id) throws EntityNotFoundException {
Session session = sessionFactory.getCurrentSession();
session.remove(session.load(classInstance, id));
}
public void remove(@NonNull T entity) {
Session session = sessionFactory.getCurrentSession();
session.remove(entity);
}
}
【问题讨论】:
-
@Autowired 注解描述了 SessionFactory 对象的依赖注入。你到底在写什么单元测试?你在测试
AbstractBaseEntityGenericDao里面的方法吗? -
是的。也许它更像是一个集成测试,但无论如何......