java怎么测试dao_java-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, 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());
現(xiàn)在,我想測試帶有假參數(shù)paramEntityId和paramEntityType的getChildren將使用模擬方法正確返回WrapperProject 1和01/01/2000,但我不知道如何啟動read方法來告訴她使用模擬方法道
解決方法:
您的代碼不適合測試,尤其是這兩行對測試非常不利:
EntityDao entityDao = new EntityDao();
UserDao userDao = new UserDao();
該代碼應(yīng)從此方法移至Factory或使用諸如Spring的容器注入(依賴注入).
僅Mockito不能測試這樣的代碼.您的方法只能做一件事,創(chuàng)建Daos是另一項工作.
標(biāo)簽:mocking,junit,dao,mockito,java
來源: https://codeday.me/bug/20191029/1963844.html
總結(jié)
以上是生活随笔為你收集整理的java怎么测试dao_java-Mockito使用模拟对象测试DAO的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python内置模块re_常用内置模块(
- 下一篇: JAVA实现inotify一样的功能_哪