好的,代码如下
使用 MockitoJUnitRunner 运行测试,并在 @Before
方法中执行
MockitoAnnotations.initMocks(this);
@Test
public void verifyTimestampTest(){
TargetHistoryPK tHistoryPK = Mockito.mock(TargetHistoryPK.class);
targetHistoryDAO = Mockito.mock(TargetHistoryDAOimpl.class);
session = Mockito.mock(Session.class);
sessionFactory = Mockito.mock(SessionFactory.class);
Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session);
TargetHistory th = Mockito.mock(TargetHistory.class);
Mockito.when(session.save(th)).thenReturn(tHistoryPK);
boolean h = targetHistoryDAO.addTargetHistory(th);
System.out.println("erh: "+ th.getTarget_update() + h);
assertNotNull("Timestamp is null", th.getTarget_update());
}
及测试方法
public class TargetHistoryDAOimpl implements TargetHistoryDAO {
@Autowired
private SessionFactory sessionFactory;
public TargetHistoryDAOimpl() {
}
public TargetHistoryDAOimpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public boolean addTargetHistory(TargetHistory th) {
if(th.getTarget_update() == null){
Date now = new Date();
Timestamp timestamp = new Timestamp(now.getTime());
th.setTarget_update(timestamp);
}
Session session = sessionFactory.getCurrentSession();
TargetHistoryPK pk = (TargetHistoryPK)session.save(th);
if(pk != null)
return true;
return false;
}
}
通常 addTargetHistory()
是从下面介绍的服务类方法调用的
@Transactional
public boolean registerTargetActivity(TargetHistory th) {
// TODO Auto-generated method stub
return targetHistoryDao.addTargetHistory(th);
}
有人可以向我解释为什么我的测试 verifyTimestampTest()
失败吗?
编辑我在测试中添加了一行(我无法调试 - 尝试调试时出现 sts 错误)
if(th == null)
System.out.println("rggrgr");
像这样
@Test
public void verifyTimestampTest(){
TargetHistoryPK tHistoryPK = Mockito.mock(TargetHistoryPK.class);
targetHistoryDAO = Mockito.mock(TargetHistoryDAOimpl.class);
session = Mockito.mock(Session.class);
sessionFactory = Mockito.mock(SessionFactory.class);
Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session);
TargetHistory th = new TargetHistory();
Mockito.when(session.save(th)).thenReturn(tHistoryPK);
boolean h = targetHistoryDAO.addTargetHistory(th);
if(th == null)
System.out.println("targetHistory is null!");
System.out.println("erh: "+ th.getTarget_update() + h);
assertNotNull("Timestamp is null", th.getTarget_update());
}
我收到 sts 警告“死代码”。为什么????为什么是死代码?
最佳答案
这是因为您的 TargetHistory th 是一个模拟。您没有为该模拟的方法设置任何行为。这就是为什么他们什么也不做并返回 null。上 this Mockito documentation page它说:
By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, ... for int/Integer, boolean/Boolean, ...).
Beware that void methods on mocks do nothing by default!
您需要将 TargetHistory 模拟替换为真实对象或 stub 。
关于java - 使用 Mockito 模拟 Hibernate 的 SessionFactory 时测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31284737/