mercredi 27 juillet 2016

unit test mockUser

How can I use @WithMockUser annotation in my unit test and then retrieve this user into my controller under test?

@PreAuthorize("hasRole('ROLE_ADMIN')")
    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<User> createUser(@RequestBody CustomerRestModel user, HttpServletRequest httpServletRequest) {
        try {
            Principal principal = httpServletRequest.getUserPrincipal();
            User u = userService.findByLogin(principal.getName());
            User newUser = new User(user.getEmail(), user.getPassword(), user.getName());
......

and this is my test

@Test
    @WithMockUser(username="admin",roles={"ROLE_ADMIN"})
    public void signUserUp() throws Exception {
        String user = json(new User("Jon Do", "password", "jon"));
        CustomerRestModel customerRestModel = new CustomerRestModel();
        customerRestModel.setEmail("name");
        customerRestModel.setName("new user");
        customerRestModel.setPassword("password");
        mvc.perform(post("/api/users")
                .contentType(contentType)
                .content(user))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.name").value("Jon Do"))
                .andExpect(jsonPath("$.parent.name").value("Elvis Costello"));

    }

Aucun commentaire:

Enregistrer un commentaire