我使用的春天在我的項目+休眠和下面是我的Java代碼懲戒Spring + Hibernate的使用mockmvc和
@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;
}
}
下面是我的單元測試,我試圖嘲弄hibernateSessionFactory。
@Test
@Transactional
public void getListOfDomainFromDomainImpl() throws Exception{
String queryForDomains = "from Domain";
Domain domainOne = new Domain();
domainOne.setDomainId(4);
domainOne.setDomainName("ADP");
Domain domainSecond = new Domain();
domainSecond.setDomainId(11);
domainSecond.setDomainName("ABP");
List<Domain> domains = new ArrayList<Domain>();
domains.add(domainOne);
domains.add(domainSecond);
DomainDaoImpl domainDaoImpl = new DomainDaoImpl();
domainDaoImpl = mock(DomainDaoImpl.class);
when(domainDaoImpl.getListOfALMDomains()).thenReturn(domains);
this.hibernateSessionFactory = mock(SessionFactory.class);
when(hibernateSessionFactory.getCurrentSession().
createQuery(queryForDomains) .list()).thenReturn(domains);
}
}
我在行
when(hibernateSessionFactory.getCurrentSession().
createQuery(queryForDomains).list()).thenReturn(domains);
得到NullPointerException異常,我沒有得到的方式來嘲笑hibernateSessionFactory。有人可以幫助解決這個問題嗎?
非常感謝。這工作 – Nagendra