Spring MVC Controller Exception Test

20.5k views Asked by At

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

There are 1 answers

3
Agung Setiawan On

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