mardi 12 février 2019

Exception is not thrown when using Mockito's doThrow method

I am working with a mocked object like the following:

@Mock
private RecipeService recipeService

I also have the following method inside the test class:

    @Test
    public void testAddRecipeWithNonUniqueName() throws Exception {
        Recipe recipe = new Recipe();

        doThrow(Exception.class)
                .when(recipeService)
                .save(recipe);

        mockMvc.perform(post("/recipes/add-recipe")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("id", "1")
                .param("name", "recipe1")
                .param("category", Category.BREAKFAST.toString())
                .param("prepTimeHour", "1")
                .param("cookTimeHour", "2")
                .param("photoUrl", "http://www.google.com"))
                .andExpect(status().is3xxRedirection())
                .andExpect(view().name("redirect:/recipes/add"));
    }

As you can see, I am using mockito's doThrow method to decide what exception is going to be thrown when the void method named save is called.

I want to make a POST request using a MockMvc object. So the method marked with the /recipes/add-recipe endpoint will be called inside one of my controller classes. The following snippet of code shows that method in detail:

    @RequestMapping(value = "/recipes/add-recipe", method = RequestMethod.POST)
    public String addRecipe(@Valid Recipe recipe, BindingResult result, RedirectAttributes redirectAttributes,
                            @AuthenticationPrincipal User user){

       String response = validateFormValues(recipe, redirectAttributes, result,
               "redirect:/recipes/add");
       if(!response.isEmpty())return response;

        recipe.setUser(user);

        try {
            recipeService.save(recipe);
        }catch(Exception e){
            redirectAttributes.addFlashAttribute("uniqueConstraintError",
                    String.format("The name \"%s\" is already taken by another recipe. " +
                                    "Please try again!",
                            recipe.getName()));
            return "redirect:/recipes/add";
        }

        setUserForIngredientsAndSteps(recipe);

        redirectAttributes.addFlashAttribute("flash",
                new FlashMessage("The recipe has been added successfully!", FlashMessage.Status.SUCCESS));
        return String.format("redirect:/recipes/%s/detail", recipe.getId());
    }

The above method contains a try-catch block. When the recipeService.save() is called, I am expecting that an exception will be thrown, and handled by the catch block. But that doesn't happen. Instead, the other lines are executed.

What am I missing ?

Aucun commentaire:

Enregistrer un commentaire