[英]How to mock Abstract class method?
I need to test a class that extends an abstract class and uses it protected method.我需要测试一个 class 扩展抽象 class 并使用它受保护的方法。 Here is the code:
这是代码:
public class DataDaoImpl extends SuperDao<CustomClass>
{
public List<Long> findAllbyId(Long productId)
{
Session session = getCurrentSession();
.......
//Rest of code
}
}
and here is the code of abstract class:这是抽象class的代码:
public abstract class SuperDao<T>
{
protected final Session getCurrentSession()
{
return sessionFactory.getCurrentSession();
}
}
Now how should I write unit test for DataDaoImpl
and should mock session in Session session = getCurrentSession();
现在我应该如何为
DataDaoImpl
编写单元测试并且应该在Session session = getCurrentSession();
? ?
I have tried different solutions on Stackoverflow but I am still not able to mock it and get session mock.我在 Stackoverflow 上尝试了不同的解决方案,但我仍然无法模拟它并获得 session 模拟。
I have tried using mocking getcurrentSession()
as suggested in answer with following code:我已经尝试使用 mocking
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);
}
But still session.getCurrentSession()
fails.但是
session.getCurrentSession()
仍然失败。
As DataDaoImpl
extends SuperDao
, method getCurrentSession
inherently becomes a part of DataDaoImpl
and you should avoid mocking the class being tested.由于
DataDaoImpl
扩展SuperDao
,方法getCurrentSession
固有地成为DataDaoImpl
的一部分,您应该避免 mocking 被测试的 class 。
What you need to do is, mock SessionFactory
and return mocked object when sessionFactory.getCurrentSession()
is called.您需要做的是,模拟
SessionFactory
并在调用sessionFactory.getCurrentSession()
时返回模拟的 object。 With that getCurrentSession
in DataDaoImpl
will return the mocked object.使用
DataDaoImpl
中的getCurrentSession
将返回模拟的 object。
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.