Question

I would like to test this DAO method

//in GrabDao.java
public WrapperProject getChildren(Integer entityId, String entityType){

    EntityDao entityDao = new EntityDao();
    UserDao userDao = new UserDao();

    EntityBase entity = entityDao.getEntityById(entityId, entityType);
    Date dateProjet = userDao.getOrganismeFromSession().getExercice().getDateProjet();

    return new Wrapper(dateProjet, entity);
}

This is what I've tried so far

    //in GrabDaoTest.java
    Integer paramEntityId = 1; 
    String paramEntityType = "type";

    EntityBase entityBase = Mockito.mock(EntityBase.class);

    EntityDao entityDao = Mockito.mock(EntityDao.class);
    when(entityDao.getEntityById(paramEntityId, paramEntityType)).thenReturn(entityBase);

    UserDao userDao = Mockito.mock(UserDao.class);
    Organisme organisme = Mockito.mock(Organisme.class);
    Exercice excercice = Mockito.mock(Exercice.class);

    when(userDao.getOrganismeFromSession()).thenReturn(organisme);
    when(organisme.getExercice()).thenReturn(excercice);
    when(userDao.getOrganismeFromSession().getExercice().getDateProjet()).thenReturn(new GregorianCalendar(2000, 01, 01).getTime());

Now I would like to test that the getChildren with fake params paramEntityId and paramEntityType will correctly return a WrapperProject 1 and 01/01/2000 using the mocked methods but I can't figured out how to launch the read method telling her to use the mocked dao

Was it helpful?

Solution

Your code is not test friendly, especially this two lines are very bad for testing:

EntityDao entityDao = new EntityDao();
UserDao userDao = new UserDao();

This code should be moved from this method to Factory or injected with containter like Spring (Dependency Injection).

Mockito alone can't test code like this. Your method should do one thing only, creating Daos is other job.

I will recommend you two films from GoogleTechTalks:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top