簡體   English   中英

使用Mockito的doThrow方法時不會引發異常

[英]Exception is not thrown when using Mockito's doThrow method

我正在使用如下所示的模擬對象:

@Mock
private RecipeService recipeService

我在測試類中也有以下方法:

    @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"))
                .andExpect(status().is3xxRedirection())
                .andExpect(view().name("redirect:/recipes/add"));
    }

如您所見,我正在使用doThrowdoThrow方法來確定調用名為savevoid方法時將引發什么異常。

我想使用MockMvc對象發出POST請求。 因此,標有/recipes/add-recipe端點的方法將在我的一個控制器類中調用。 以下代碼片段詳細顯示了該方法:

    @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());
    }

上面的方法包含一個try-catch塊。 期望在調用recipeService.save()時,將引發異常,並由catch塊進行處理。 但這不會發生。 而是執行其他行。

我想念什么?

僅當保存之前創建的特定配方時,才會觸發正在調用的doTrhow()方法。

你需要告訴Mockito扔任何食譜

Mockito.doThrow(Exception.class)
            .when(recipeService)
            .save(Mockito.any(Recipe.class));
Recipe recipe = new Recipe();

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

只有將完全相同的Recipe實例傳遞給save方法時,此代碼才有效。 如果實現了equals和/或hashCode方法傳遞給Recipe實例,則預期值1name可能使其起作用。

Recipe recipe = new Recipe();
recipe.setId(1);
recipe.setName("name");

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

但是,由於您可能想測試錯誤情況,因此始終拋出異常可能更容易。 為此,請使用any()匹配器。

doThrow(Exception.class)
        .when(recipeService)
        .save(any(Recipe.class);

現在,調用save時,無論在Recipe傳遞了什么,都會引發異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM