我想测试这种DAO方法
//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);
}
这是我到目前为止尝试过的
//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());
现在,我想测试带有假参数paramEntityId和paramEntityType的getChildren将使用模拟方法正确返回WrapperProject 1和01/01/2000,但我不知道如何启动read方法来告诉她使用模拟方法道
解决方法:
您的代码不适合测试,尤其是这两行对测试非常不利:
EntityDao entityDao = new EntityDao();
UserDao userDao = new UserDao();
该代码应从此方法移至Factory或使用诸如Spring的容器注入(依赖注入).
仅Mockito不能测试这样的代码.您的方法只能做一件事,创建Daos是另一项工作.
标签:mocking,junit,dao,mockito,java
来源: https://codeday.me/bug/20191029/1963844.html