Spring MVC控制器异常测试

时间:2013-08-09 16:38:26

标签: spring-mvc spring-mvc-test springmockito

我有以下代码

@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"));

1 个答案:

答案 0 :(得分:15)

最后我解决了。由于我使用独立设置进行spring mvc控制器测试,所以我需要在每个需要执行异常检查的控制器单元测试中创建 HandlerExceptionResolver

mockMvc= MockMvcBuilders.standaloneSetup(adminCategoryController).setSingleView(view)
            .setValidator(validator()).setViewResolvers(viewResolver())
            .setHandlerExceptionResolvers(getSimpleMappingExceptionResolver()).build();

然后测试代码

@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"));
}