Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring mvc SpringMVC控制器异常测试_Spring Mvc_Spring Mvc Test_Springmockito - Fatal编程技术网

Spring mvc SpringMVC控制器异常测试

Spring mvc SpringMVC控制器异常测试,spring-mvc,spring-mvc-test,springmockito,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){

我有以下代码

@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));
}
Mockito.when(categoryService.findOne(1L)).thenThrow(new NotFoundException("Message"));
但失败了。 有没有关于如何测试异常的建议

或者我应该在CategoryService中抛出异常,以便执行类似的操作

@Test(expected = NotFoundException.class)
public void editFormNotFoundTest() throws Exception{

    Mockito.when(categoryService.findOne(1L)).thenReturn(null);
    mockMvc.perform(get("/admin/category/edit/{id}",1L));
}
Mockito.when(categoryService.findOne(1L)).thenThrow(new NotFoundException("Message"));

我终于解决了。因为我在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"));
}

什么是getSimpleMappingExceptionResolver()实现?我发现了以下内容:。看起来,org.springframework.web.servlet.handler.SimpleMappingExceptionResolver已经是一个Springclass@josete域名已更改