我需要测试一个扩展抽象类并使用它的受保护方法的类。这是代码:
public class DataDaoImpl extends SuperDao<CustomClass>
{
public List<Long> findAllbyId(Long productId)
{
Session session = getCurrentSession();
.......
//Rest of code
}
}
这是抽象类的代码:
public abstract class SuperDao<T>
{
protected final Session getCurrentSession()
{
return sessionFactory.getCurrentSession();
}
}
现在我应该如何编写单元测试DataDaoImpl并且应该模拟会话Session session = getCurrentSession();?
我在 Stackoverflow 上尝试了不同的解决方案,但我仍然无法模拟它并获得会话模拟。
我尝试使用getcurrentSession()以下代码回答中建议的模拟:
@Test
public void testDataDaoImpl()
{
SessionFactory mockedSessionFactory = Mockito.mock(SessionFactory.class);
Session mockedSession = Mockito.mock(Session.class);
Mockito.when(mockedSessionFactory.getCurrentSession()).thenReturn(mockedSession);
DataDaoImpl DDI_Instance = new DataDaoImpl((long) 120);
DDI_Instance.findAllbyId(Long productId);
}
但仍然session.getCurrentSession()失败。