【问题标题】:Mockito test DAO with mocked objectsMockito 使用模拟对象测试 DAO
【发布时间】:2014-01-30 17:36:11
【问题描述】:

我想测试这个 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 将正确返回 WrapperProject 1 和 01/01/ 2000 using the mocked methods 但我不知道如何启动 read 方法告诉她使用 mocked dao

【问题讨论】:

    标签: java junit mocking mockito dao


    【解决方案1】:

    您的代码对测试不友好,尤其是这两行对测试非常不利:

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

    此代码应从该方法移至工厂或使用 Spring 等容器注入(依赖注入)。

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

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

    【讨论】:

    • 谢谢,你是对的,我会看他们并在这里发布我的最终工作答案
    • 我完全同意 MariuszS 的观点。在my article on the Mockito wiki 中,我提到了几种可以使用 Mockito 来帮助测试创建新对象的代码的方法。快速浏览一下,看看它们中的任何一个是否可能在这里有用。
    • 说 Mockito 根本不支持模拟 new-ed 对象不是更正确吗?因为如果确实如此(这是完全可能的),getChildren 方法将很容易按原样进行测试。而且 DI 不是替代使用 new 的方法;这是一种“配置与使用分离”的方式,这里似乎并非如此。
    • @Rogério DI 让单元测试变得更加容易。 programmers.stackexchange.com/questions/140992/…
    • @MariuszS 好吧,这个问题的大多数答案都说“不”。当然,现实情况是,单元测试的难易程度与 DI 或没有 DI 无关,而是与将被测单元与外部依赖项隔离的能力有关。例如,PowerMockito 是一个模拟/隔离工具,无论有没有 DI,它都能很好地完成这项工作。通常,当人们谈论这些假定的可测试性问题时,他们似乎并没有意识到已经存在适当的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多