Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Controller Exception Test

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"));
like image 282
Agung Setiawan Avatar asked Aug 09 '13 16:08

Agung Setiawan


People also ask

How does spring boot controller handle exceptions?

Exception Handler Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API.

How do I test Restcontroller in spring boot?

React Full Stack Web Development With Spring Boot Spring Boot provides an easy way to write a Unit Test for Rest Controller file. With the help of SpringJUnit4ClassRunner and MockMvc, we can create a web application context to write Unit Test for Rest Controller file.

How do you write JUnit for ExceptionHandler?

Here is the outline of the class: @Controller public class MyController{ @RequestMapping(..) public void myMethod(...) throws NotAuthorizedException{...} @ExceptionHandler(NotAuthorizedException.


1 Answers

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"));
}
like image 147
Agung Setiawan Avatar answered Oct 28 '22 23:10

Agung Setiawan