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"));
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.
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.
Here is the outline of the class: @Controller public class MyController{ @RequestMapping(..) public void myMethod(...) throws NotAuthorizedException{...} @ExceptionHandler(NotAuthorizedException.
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"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With