我有以下代码
@RequestMapping(value = "admin/category/edit/{id}",method = RequestMethod.GET)
public String editForm(Model model,@PathVariable Long id) throws NotFoundException{
Category category=categoryService.findOne(id);
if(category==null){
throw new NotFoundException();
}
model.addAttribute("category", category);
return "edit";
}
我正在尝试在引发 NotFoundException 时进行单元测试,所以我编写了这样的代码
@Test(expected = NotFoundException.class)
public void editFormNotFoundTest() throws Exception{
Mockito.when(categoryService.findOne(1L)).thenReturn(null);
mockMvc.perform(get("/admin/category/edit/{id}",1L));
}
但是失败了。有什么建议如何测试异常吗?
或者我应该在 CategoryService 中抛出异常,这样我就可以做这样的事情
Mockito.when(categoryService.findOne(1L)).thenThrow(new NotFoundException("Message"));