繁体   English   中英

Mockito用模拟对象测试DAO

[英]Mockito test DAO with mocked objects

我想测试这个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());

现在我想测试带有伪参数的getChildren paramEntityIdparamEntityType将使用模拟方法正确返回WrapperProject 1和01/01/2000 但我无法弄清楚如何启动read方法告诉她使用mocked道

你的代码不是测试友好的,特别是这两行测试非常糟糕:

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

此代码应从此方法移至Factory或使用类似Spring(依赖注入)的类似注入。

仅靠Mockito无法测试这样的代码。 你的方法应该只做一件事,创建Daos是其他工作。

我会推荐你​​两部来自GoogleTechTalks的电影:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM