亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Mockito 測試服務的刪除方法

使用 Mockito 測試服務的刪除方法

智慧大石 2023-10-12 17:19:02
我嘗試為我的刪除方法進行服務模擬測試。這是我的RestoranServiceImpl.java中的刪除方法public void deleteRestoran(Long idRestoran) {        RestoranModel restoran = getRestoranByIdRestoran(idRestoran).get();        if(restoran.getListMenu().size()==0){            restoranDb.delete(restoran);        }else{            UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException();            throw unsupportedOperationException;        }    }這是我的RestoranDb.javapublic interface RestoranDb extends JpaRepository<RestoranModel,Long> {    Optional<RestoranModel> findByIdRestoran(Long idRestoran);}這是到目前為止我的刪除方法@Test    public void whenDleleteValidRestoranItShouldCallRestoranRepositoryDelete() {        RestoranModel newRestoran = new RestoranModel();        newRestoran.setIdRestoran((long) 1);        newRestoran.setNama("mekdi");        newRestoran.setAlamat("pacil");        newRestoran.setNomorTelepon(14045);        restoranService.addRestoran(newRestoran);        verify(restoranDb, times(1)).save(newRestoran);        System.out.println(restoranService.getRestoranList().size());        when(restoranDb.findByIdRestoran((long)1).get()).thenReturn(newRestoran).thenReturn(null);        restoranService.deleteRestoran(newRestoran.getIdRestoran());        verify(restoranDb, times(1)).delete(newRestoran);    }當我嘗試運行它時,我收到此錯誤。java.util.NoSuchElementException: No value present我試圖四處尋找解決方案,但找不到適合我的解決方案。
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

我認為你在這里模擬了錯誤的方法,你應該模擬RestoranDb.findByIdRestoran方法,而不是Optional.get方法

when(restoranDb.findByIdRestoran((long)1).get()).thenReturn(newRestoran).thenReturn(null);

應該

when(restoranDb.findByIdRestoran((long)1)).thenReturn(Optional.of(newRestoran));


查看完整回答
反對 回復 2023-10-12
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號