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