samedi 22 juin 2019

Spring testing mocking findById not working

I'm trying to mock the process of finding an object from a service by an Id and it will return back the object. However, when trying to do so I get an error.

Request method

@PreAuthorize("hasRole('ROLE_ADMIN') or @recipeRepository.findById(#id).get()?.owner.username == authentication.name")
    @RequestMapping(path = "/recipes/{id}/edit", method = RequestMethod.GET)
    public String editRecipe(Model model, @PathVariable("id") Long id) {
        Recipe recipe = recipeService.findById(id);
        model.addAttribute("task", "Edit recipe");
        model.addAttribute("buttonAction", "Save");
        model.addAttribute("action", String.format("/recipes/%d/edit", id));

        if (!model.containsAttribute("recipe")) {
            model.addAttribute("recipe", recipe);
        }

        if (recipe.getPhoto() != null) {
            model.addAttribute("photo", true);
        }

        return "edit";
    }

Test method

@Test
    @WithUserDetails("daniel")
    public void editRecipePageLoadsWithRecipeOwner() throws Exception {
        Recipe recipe = recipeBuilder(1L);
        User user = userBuilder();
        recipe.setOwner(user);

        when(recipeService.findById(1L)).thenReturn(recipe);

        mockMvc.perform(get("/recipes/1/edit"))
                .andExpect(status().isOk())
                .andExpect(model().attributeExists("task", "buttonAction", "action", "recipe"));
    }

Service method

@Override
    public Recipe findById(Long id) {
        Optional<Recipe> recipe = recipes.findById(id);
        if (recipe.isPresent()) {
            return recipe.get();
        }
        System.out.println(id + " is not in db");
        // TODO:drt - Create new exception to handle this
        throw new RuntimeException();
    }

I expect this process to be mocked correctly but instead I get this error:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.util.NoSuchElementException: No value present

I'm only guessing that the no value present is from the findById service method, so what did I do wrong? Can anyone help? Thanks

Aucun commentaire:

Enregistrer un commentaire