0

我需要测试一个扩展抽象类并使用它的受保护方法的类。这是代码:

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()失败。

4

1 回答 1

2

作为DataDaoImplextends SuperDao,方法getCurrentSession本质上成为其中的一部分,DataDaoImpl你应该避免模拟被测试的类。

您需要做的是,在调用SessionFactory时模拟并返回模拟对象sessionFactory.getCurrentSession()。有了它getCurrentSessionDataDaoImpl将返回模拟对象。

希望能帮助到你。

于 2019-10-30T06:39:54.183 回答