mercredi 22 juin 2016

Mocking spring + hibernate using mockmvc and mockito

I am using spring + hibernate in my project and below is my java code

 @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;
      }
     }

Below is my unit test and I am try to mock 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);
}
}

I am getting NullPointerException at line

 when(hibernateSessionFactory.getCurrentSession().
 createQuery(queryForDomains).list()).thenReturn(domains);

I am not getting a way to mock hibernateSessionFactory. Can someone please help on this issue?

Aucun commentaire:

Enregistrer un commentaire