概述
我有一个班级:
public class ProductComercialOrderDAO extends BaseDao implements ProductComercialOrderDAOLocal {
private final static Logger log = UtilsBusiness.getLog4J(ProductComercialOrderDAO.class);
public Session getSession() throws DAOServiceException{
return super.getSession();
}
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void createProductComertialOrder(ProductComertialOrder pcom) throws DAOServiceException, DAOSQLException {
log.debug("== Init createProductComertialOrder/ProductComercialOrderDAO ==");
Session session = this.getSession();
try {
session.save(pcom);
this.doFlush(session);
} catch (Throwable ex) {
log.error("== Exception in ProductComertialOrder ==");
throw super.manageException(ex);
} finally {
log.debug("== createProductComertialOrder/ProductComercialOrderDAO End ==");
}
}
}
我需要模拟方法:
public Session getSession() throws DAOServiceException{
return super.getSession();
}
用于在jUnit测试阶段替换Hibernate数据源.
我和Mockito有这个代码:
package dao;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.Date;
import javax.ejb.EJB;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import co.com.myapp.sdii.exceptions.DAOSQLException;
import co.com.myapp.sdii.exceptions.DAOServiceException;
import co.com.myapp.sdii.model.pojo.ProductComercialOrder;
import co.com.myapp.sdii.persistence.dao.core.impl.ProductComercialOrderDAO;
import co.com.myapp.sdii.persistence.hibernate.HibernateUtil;
public class ProductComercialOrderDAOTest {
public ProductComercialOrderDAO prodcomDao;
private ProductComercialOrder prodCom;
SessionFactory sessionFact = null;
Session session = null;
@Test
public void setUp() throws DAOServiceException, DAOSQLException{
sessionFact = util.HibernateUtil.getSessionFactory();
sessionFact.openSession();
session = sessionFact.getCurrentSession();
prodCom = new ProductComercialOrder();
prodCom.setCreationDate(new Date());
prodCom.setCreationUser("user1");
prodCom.setId(1L);
prodCom.setPrdCategory("Hardware");
prodCom.setPrdCategoryType("IRD");
prodCom.setOrderNum(1L);
if(prodcomDao == null){
prodcomDao = new ProductComercialOrderDAO();
}
Mockito.spy(ProductComercialOrder.class);
Mockito.when(prodcomDao.getSession()).thenReturn(session);
prodcomDao.createProductComercialOrder(prodCom);
}
}
但是当我打电话时:
prodcomDao.createProductComercialOrder(prodCom);
调用原始的ProductComercialOrderDAO.getSession(),而不是我的模拟.
我如何模拟替换hibernate会话的方法?
最佳答案 你需要这样做
Mockito.doReturn(会话).当(prodcomDao).getSession()
确保不调用原始方法.
最后
以上就是无聊铅笔为你收集整理的java替换方法_java – Mockito替换方法的全部内容,希望文章能够帮你解决java替换方法_java – Mockito替换方法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复