【问题标题】:Spring MVC Controller Exception TestSpring MVC 控制器异常测试
【发布时间】:2013-08-11 16:10:51
【问题描述】:

我有以下代码

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2021-04-01
    • 2017-12-11
    相关资源
    最近更新 更多