我正在使用Spring Security,并面向控制器的问题编写单元测试用例(使用MockMvc)。
我的控制器中有一个方法,如下所示:
@GetMapping
public ResponseEntity<User> getUser(@AuthenticationPrincipal User activeUser){
String userEmail = activeUser.getEmail();
return userService.getUser(userEmail);
}
我得到500错误。
我试过的控制器的另一个变种是,这是在Postman / Curl上工作的:
@GetMapping
public ResponseEntity<User> getUser(OAuth2Authentication authentication){
String userEmail = (String) authentication.getUserAuthentication().getPrincipal();
return userService.getUser(userEmail);
}
我的服务看起来像:
public ResponseEntity<User> getUser(String email) {
return userRepository.findByEmail(email)
.map(record -> ResponseEntity.ok().body(record))
.orElse(ResponseEntity.notFound().build());
}
在我的控制器方法的单元测试用例中,我有:
@Test
@WithMockUser(username = "1", password = "pwd", roles = "USER")
public void controller_should_get_user() throws Exception {
when(userService.getUser("1")).thenReturn(new ResponseEntity(userMock, HttpStatus.OK));
this.mockMvc.perform(MockMvcRequestBuilders.get("/api/user/")).andExpect(status().isOk());
}
我收到以下错误:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at com.timecloud.user.controller.UserControllerTest.controller_should_get_user(UserControllerTest.java:60)
我应该如何使用当前身份验证传递或模拟用户?谢谢。
NullPointerException
即将到来,因为你的测试无法为OAuth2Authentication
对象找到任何东西。您可以在测试用例中执行两项操作:
OAuth2Authentication
。要么
@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void mytest1() throws Exception {
//Your test scenario
}