Test d'exception du contrôleur Spring MVC
J'ai le code suivant
@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";
}
Je suis en train de test de l'unité lorsque NotFoundException est jeté, j'ai donc écrire du code comme ceci
@Test(expected = NotFoundException.class)
public void editFormNotFoundTest() throws Exception{
Mockito.when(categoryService.findOne(1L)).thenReturn(null);
mockMvc.perform(get("/admin/category/edit/{id}",1L));
}
Mais a échoué.
Des suggestions pour tester l'exception?
Ou devrais-je jeter l'exception à l'intérieur de CategoryService si je peux faire quelque chose comme ceci
Mockito.when(categoryService.findOne(1L)).thenThrow(new NotFoundException("Message"));
source d'informationauteur Agung Setiawan
Vous devez vous connecter pour publier un commentaire.
Enfin je l'ai résolu. Depuis que je suis en utilisant d'installation autonome pour spring mvc contrôleur de test, donc j'ai besoin de créer HandlerExceptionResolver dans chaque contrôleur de test de l'unité qui doit effectuer l'exception de la vérification.
Puis le code pour tester