13

我有以下代码

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

1 回答 1

16

最后我解决了。由于我为 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"));
}
于 2013-08-10T00:42:51.657 回答