单元测试mockUser

时间:2016-07-27 07:26:56

标签: spring unit-testing spring-security spring-mvc-test

如何在单元测试中使用@WithMockUser注释,然后将此用户检索到我测试的控制器中?

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

这是我的测试

@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"));

    }

0 个答案:

没有答案