Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 单元测试模拟用户_Spring_Unit Testing_Spring Security_Spring Mvc Test - Fatal编程技术网

Spring 单元测试模拟用户

Spring 单元测试模拟用户,spring,unit-testing,spring-security,spring-mvc-test,Spring,Unit Testing,Spring Security,Spring Mvc Test,如何在单元测试中使用注释,然后将该用户检索到被测控制器中 @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<User> createUser(@RequestBody Customer

如何在单元测试中使用注释,然后将该用户检索到被测控制器中

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

由于您链接到的文档声明“ROLE_uu是自动添加的”,我想您应该只在@WithMockUser注释中设置roles={“ADMIN”},但principal为null!
@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"));

    }