Spring 模拟弹簧&x2B;使用mockmvc和mockito进行hibernate
我在我的项目中使用spring+hibernate,下面是我的java代码Spring 模拟弹簧&x2B;使用mockmvc和mockito进行hibernate,spring,hibernate,unit-testing,mockito,mockmvc,Spring,Hibernate,Unit Testing,Mockito,Mockmvc,我在我的项目中使用spring+hibernate,下面是我的java代码 @Repository @Transactional public class DomainDaoImpl implements DomainDao { static Logger logger = LoggerFactory.getLogger(DomainDaoImpl.class); @Autowired private SessionFactory hibern
@Repository
@Transactional
public class DomainDaoImpl implements DomainDao {
static Logger logger = LoggerFactory.getLogger(DomainDaoImpl.class);
@Autowired
private SessionFactory hibernateSessionFactory;
private static final String queryForDomains = "from Domain";
@Override
public List<Domain> getListOfALMDomains() throws CustomException {
logger.info("Getting List of ALM domains");
List<Domain> domains = null;
try {
Session session = null;
domains = this.hibernateSessionFactory.getCurrentSession().createQuery(queryForDomains).list();
logger.info("Exiting getListOfALMDomains method");
} catch (Exception e) {
logger.error("Exception occurred : " + e);
throw new CustomException("Please contact your administrator. Unable to retrieve the domains.");
}
return domains;
}
}
我没有办法模仿工厂。有人能在这个问题上帮忙吗
Session Session=mock(Session.class);
Query=mock(Query.class);
当(hibernateSessionFactory.getCurrentSession())。然后返回(会话);
当(session.createQuery(anyString())。然后返回(query);
when(query.list()).thenReturn(域);
domainDaoImpl.setSessionFactory(hibernateSessionFactory)代码>
您没有此方法,因此必须添加它,并在此方法上使用@Autowired,而不是在字段上使用@Autowired:
@Autowired
public void setSessionFactory(SessionFactory sf) {this.hibernateSessionFactory = sf;}
在测试中将模拟会话工厂设置为DomainDaoImpl:
domainDaoImpl.setSessionFactory(hibernateSessionFactory)代码>
您必须一直模拟list()方法:
Session Session=mock(Session.class);
Query=mock(Query.class);
当(hibernateSessionFactory.getCurrentSession())。然后返回(会话);
当(session.createQuery(anyString())。然后返回(query);
when(query.list()).thenReturn(域);
不要模仿DomainDaoImpl,因为这是您正在测试的类
domainDaoImpl.setSessionFactory(hibernateSessionFactory)代码>
您没有此方法,因此必须添加它,并在此方法上使用@Autowired,而不是在字段上使用@Autowired:
@Autowired
public void setSessionFactory(SessionFactory sf) {this.hibernateSessionFactory = sf;}
在测试中将模拟会话工厂设置为DomainDaoImpl:
domainDaoImpl.setSessionFactory(hibernateSessionFactory)代码>使用这些代码行
Session session = mock(Session.class);
SessionFactory sessionFactory = mock(SessionFactory.class);
Query query = mock(Query.class);
when(sessionFactory.getCurrentSession()).thenReturn(session);
when(session.createQuery(queryForDomains)).thenReturn(query );
when(query.list()).thenReturn(domains);
使用这些代码行
Session session = mock(Session.class);
SessionFactory sessionFactory = mock(SessionFactory.class);
Query query = mock(Query.class);
when(sessionFactory.getCurrentSession()).thenReturn(session);
when(session.createQuery(queryForDomains)).thenReturn(query );
when(query.list()).thenReturn(domains);