Spring MVC Controller Exception Test

Agung Setiawan picture Agung Setiawan · Aug 9, 2013 · Viewed 18.1k times · Source

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

Answer

Agung Setiawan picture Agung Setiawan · Aug 10, 2013

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