简体   繁体   English

Mockito用模拟对象测试DAO

[英]Mockito test DAO with mocked objects

I would like to test this DAO method 我想测试这个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);
}

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

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). 此代码应从此方法移至Factory或使用类似Spring(依赖注入)的类似注入。

Mockito alone can't test code like this. 仅靠Mockito无法测试这样的代码。 Your method should do one thing only, creating Daos is other job. 你的方法应该只做一件事,创建Daos是其他工作。

I will recommend you two films from GoogleTechTalks : 我会推荐你​​两部来自GoogleTechTalks的电影:

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

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