日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java怎么测试dao_java-Mockito使用模拟对象测试DAO

發布時間:2025/4/17 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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());

現在,我想測試帶有假參數paramEntityId和paramEntityType的getChildren將使用模擬方法正確返回WrapperProject 1和01/01/2000,但我不知道如何啟動read方法來告訴她使用模擬方法道

解決方法:

您的代碼不適合測試,尤其是這兩行對測試非常不利:

EntityDao entityDao = new EntityDao();

UserDao userDao = new UserDao();

該代碼應從此方法移至Factory或使用諸如Spring的容器注入(依賴注入).

僅Mockito不能測試這樣的代碼.您的方法只能做一件事,創建Daos是另一項工作.

標簽:mocking,junit,dao,mockito,java

來源: https://codeday.me/bug/20191029/1963844.html

總結

以上是生活随笔為你收集整理的java怎么测试dao_java-Mockito使用模拟对象测试DAO的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。