我有通用抽象类AbstractBaseEntityGenericDao,其中包含@Autowired字段。直到我必须为其编写一个单元测试,而且在扩展它的类的所有测试中都没有重复相同的代码之前,它一直工作得很好。现在我在想...是否可以为此类编写单元/集成测试?
@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);
}
}
答案 0 :(得分:1)
之所以很难,是因为通常您不应该这样做。抽象类应该不知道其子类如何创建SessionFactory
。因此,它看起来应该像这样:
@Repository
@Transactional
public abstract class AbstractBaseEntityGenericDao<T extends BaseEntity> {
...
protected SessionFactory sessionFactory;
...
}
现在您不能直接对抽象类进行单元测试,因为它无法实例化。但是,您可以在单元测试中将其存根,然后对该存根进行测试。存根将具有一个用于保护字段的构造函数,我们可以在单元测试中模拟它。最终看起来像这样:
public class AbstractBaseEntityGenericDaoTest {
private class AbstractClassStub extends AbstractBaseEntityGenericDao {
public AbstractClassStub(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void create(BaseEntity entity) {
super.create(entity);
}
@Override
public Optional find(long id) {
return super.find(id);
}
@Override
public void update(BaseEntity entity) {
super.update(entity);
}
@Override
public void remove(@NonNull Long id) throws EntityNotFoundException {
super.remove(id);
}
@Override
public void remove(BaseEntity entity) {
super.remove(entity);
}
}
@Mock
SessionFactory sessionFactory;
private AbstractClassStub abstractClassStub;
@Before
public void before() {
sessionFactory = mock(SessionFactory.class);
abstractClassStub = new AbstractClassStub(sessionFactory);
}
@Test
public void testWhatever() {
abstractClassStub.find(1); //or whatever
}
}