日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

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

發(fā)布時(shí)間:2025/4/17 63 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java怎么测试dao_java-Mockito使用模拟对象测试DAO 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

我想測(cè)試這種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);

}

這是我到目前為止嘗試過(guò)的

//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)在,我想測(cè)試帶有假參數(shù)paramEntityId和paramEntityType的getChildren將使用模擬方法正確返回WrapperProject 1和01/01/2000,但我不知道如何啟動(dòng)read方法來(lái)告訴她使用模擬方法道

解決方法:

您的代碼不適合測(cè)試,尤其是這兩行對(duì)測(cè)試非常不利:

EntityDao entityDao = new EntityDao();

UserDao userDao = new UserDao();

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

僅Mockito不能測(cè)試這樣的代碼.您的方法只能做一件事,創(chuàng)建Daos是另一項(xiàng)工作.

標(biāo)簽:mocking,junit,dao,mockito,java

來(lái)源: https://codeday.me/bug/20191029/1963844.html

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。