2016-06-22 84 views
0
的Mockito

我使用的春天在我的項目+休眠和下面是我的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。有人可以幫助解決這個問題嗎?

回答

1
  1. 你將不得不一路嘲笑的list()方法:

Session session = mock(Session.class); Query query = mock(Query.class); when(hibernateSessionFactory.getCurrentSession()).thenReturn(session); when(session.createQuery(anyString())).thenReturn(query); when(query.list()).thenReturn(domains);

  • 不要嘲笑DomainDaoImpl因爲這是你正在測試的課程。
  • domainDaoImpl.setSessionFactory(hibernateSessionFactory);

    你沒有這個方法,所以你必須添加它,並在現場對這個方法使用@Autowired代替:

    @Autowired 
    public void setSessionFactory(SessionFactory sf) {this.hibernateSessionFactory = sf;} 
    
  • 設置你的模擬會話工廠DomainDaoImpl在您的測試:
  • domainDaoImpl.setSessionFactory(hibernateSessionFactory);

    +0

    非常感謝。這工作 – Nagendra

    0

    使用這些代碼行

    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);