我试图对删除方法的服务进行模拟测试。
这是我的 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.java
public 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
我试图四处寻找解决方案,但找不到适合我的解决方案。
答案 0 :(得分:1)
我认为您在此处模拟错误的方法,应该模拟RestoranDb.findByIdRestoran
方法,而不是Optional.get
方法
when(restoranDb.findByIdRestoran((long)1).get()).thenReturn(newRestoran).thenReturn(null);
应该是
when(restoranDb.findByIdRestoran((long)1)).thenReturn(Optional.of(newRestoran));