Spring MVC Controller Exception Test
spring-mvc, spring-mvc-test, springmockito
Solution
Finally I solved it. Since I'm using stand alone setup for spring mvc controller test so I need to create HandlerExceptionResolver in every controller unit test that needs to perform exception checking.
mockMvc= MockMvcBuilders.standaloneSetup(adminCategoryController).setSingleView(view)
.setValidator(validator()).setViewResolvers(viewResolver())
.setHandlerExceptionResolvers(getSimpleMappingExceptionResolver()).build();
Then the code to test
@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"));
}
Problem
I have the following code ``` @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"; } ``` I'm trying to unit test when NotFoundException is thrown, so i write code like this ``` @Test(expected = NotFoundException.class) public void editFormNotFoundTest() throws Exception{ Mockito.when(categoryService.findOne(1L)).thenReturn(null); mockMvc.perform(get("/admin/category/edit/{id}",1L)); } ``` But failed. Any suggestions how to test the exception? Or should i throw the exception inside CategoryService so i can do something like this ``` Mockito.when(categoryService.findOne(1L)).thenThrow(new NotFoundException("Message")); ```