[英]Mockito doesn't throw correct exception when using doThrow on a spy
[英]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"));
}
如您所见,我正在使用doThrow
的doThrow
方法来确定调用名为save
的void
方法时将引发什么异常。
我想使用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
实例,则预期值1
和name
可能使其起作用。
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.