mardi 7 juillet 2015

Test fails when mocking Hibernate's SessionFactory using Mockito

Ok, so heres the code

Test runs with MockitoJUnitRunner and in @Before method i execute MockitoAnnotations.initMocks(this);

@Test
public void verifyTimestampTest(){
    TargetHistoryPK tHistoryPK = Mockito.mock(TargetHistoryPK.class);

    targetHistoryDAO = Mockito.mock(TargetHistoryDAOimpl.class);        
    session = Mockito.mock(Session.class);
    sessionFactory = Mockito.mock(SessionFactory.class);

    Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session);

    TargetHistory th = Mockito.mock(TargetHistory.class);
    Mockito.when(session.save(th)).thenReturn(tHistoryPK);

    boolean h = targetHistoryDAO.addTargetHistory(th);

    System.out.println("erh: "+ th.getTarget_update() + h);
    assertNotNull("Timestamp is null", th.getTarget_update());
}

and tested method

public class TargetHistoryDAOimpl implements TargetHistoryDAO {


    @Autowired
    private SessionFactory sessionFactory;

    public TargetHistoryDAOimpl() {     
    }

    public TargetHistoryDAOimpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    @Override
    public boolean addTargetHistory(TargetHistory th) {

        if(th.getTarget_update() == null){
            Date now = new Date();
            Timestamp timestamp = new Timestamp(now.getTime());
            th.setTarget_update(timestamp);
        }
        Session session = sessionFactory.getCurrentSession();
        TargetHistoryPK pk = (TargetHistoryPK)session.save(th);
        if(pk != null)
            return true;

        return false;
    }

}

Normally addTargetHistory() is being called from a service class method presented below

    @Transactional
    public boolean registerTargetActivity(TargetHistory th) {
        // TODO Auto-generated method stub
        return targetHistoryDao.addTargetHistory(th);
    }

Can someone explain to me why my test verifyTimestampTest() fails?

Aucun commentaire:

Enregistrer un commentaire