我尝试为我的删除方法进行服务模拟测试。这是我的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));
添加回答
举报
0/150
提交
取消