Java 使用模拟对象的模拟测试DAO

Java 使用模拟对象的模拟测试DAO,java,junit,mocking,mockito,dao,Java,Junit,Mocking,Mockito,Dao,我想测试这个DAO方法 //in GrabDao.java public WrapperProject getChildren(Integer entityId, String entityType){ EntityDao entityDao = new EntityDao(); UserDao userDao = new UserDao(); EntityBase entity = entityDao.getEntityById(entityId, entityTy

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

现在我想测试带有伪参数的paramEntityIdparamEntityTypegetChildren是否会使用模拟方法正确返回包装项目1和2000年1月1日,但我不知道如何启动read方法,告诉她使用模拟的dao

代码对测试不友好,特别是这两行代码对测试非常不利:

EntityDao entityDao = new EntityDao();
UserDao userDao = new UserDao();
这段代码应该从这个方法转移到工厂,或者注入类似于Spring的容器(依赖项注入)

Mockito无法单独测试这样的代码。您的方法应该只做一件事,创建DAO是另一件事

我将向您推荐以下两部电影:


谢谢,你说得对,我会关注他们,并在这里发布我的最终工作答案。我完全同意MariuszS的观点。在中,我提到了使用Mockito帮助测试创建新对象的代码的几种方法。快速浏览一下,看看它们中的任何一个在这里是否有用。如果说Mockito根本不支持对新的-ed对象进行模拟,那不是更正确吗?因为如果这样做了(这是完全可能的),那么
getChildren
方法将很容易进行测试。而DI并不是取代使用新的;这是一种“将配置与使用分开”的方法,但这里的情况似乎并非如此。@Rogério DI使单元测试更加容易@这个问题的大多数答案都是否定的。当然,现实情况是,单元测试的易用性与DI或无DI无关,而是与将被测单元与其外部依赖项隔离开来的能力有关。例如,PowerMockito是一个模拟/隔离工具,无论是否使用DI,它都能很好地完成工作。通常,当人们谈论这些假定的可测试性问题时,他们似乎没有意识到已经存在适当的解决方案。