Agu*_*wan 12 spring-mvc springmockito spring-mvc-test
我有以下代码
@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";
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试在抛出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));
}
Run Code Online (Sandbox Code Playgroud)
但失败了.有关如何测试异常的任何建议吗?
或者我应该在CategoryService中抛出异常,这样我就可以做这样的事情
Mockito.when(categoryService.findOne(1L)).thenThrow(new NotFoundException("Message"));
Run Code Online (Sandbox Code Playgroud)
Agu*_*wan 15
最后我解决了.由于我使用独立设置进行spring mvc控制器测试,所以我需要在每个需要执行异常检查的控制器单元测试中创建HandlerExceptionResolver.
mockMvc= MockMvcBuilders.standaloneSetup(adminCategoryController).setSingleView(view)
.setValidator(validator()).setViewResolvers(viewResolver())
.setHandlerExceptionResolvers(getSimpleMappingExceptionResolver()).build();
Run Code Online (Sandbox Code Playgroud)
然后代码来测试
@Test
public void editFormNotFoundTest() throws Exception{
Mockito.when(categoryService.findOne(1L)).thenReturn(null);
mockMvc.perform(get("/admin/category/edit/{id}",1L))
.andExpect(view().name("404s"))
.andExpect(forwardedUrl("/WEB-INF/jsp/404s.jsp"));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15683 次 |
| 最近记录: |