我正在使用 Spring Security,并面临为 Controller 编写单元测试用例(使用 MockMvc)的问题。
我的 Controller 中有一个方法,如下所示:
@GetMapping
public ResponseEntity<User> getUser(@AuthenticationPrincipal User activeUser){
String userEmail = activeUser.getEmail();
return userService.getUser(userEmail);
}
我收到了 500 错误。
我尝试过的 Controller 的另一个变体是,这适用于 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());
}
在此 Controller 方法的单元测试用例中,我有:
@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)
我应该如何使用当前身份验证传递或模拟用户?谢谢。
最佳答案
@WithMockUser
创建 UsernameAuthenticationToken
,不是 OAuth2Authentication
.
这里至少有三个解决方案:
- 注入(inject)
OAuth2Authentication
安全上下文中的模拟或实例 - 将您的方法更改为
public ResponseEntity<User> getUser(Authentication authentication)
,然后使用authentication.getName()
里面 - 使用一些现有工具来应用解决方案
1.
对于你来说,就像这样 libs I wrote
解决方案 1 的使用示例
@Test
public void test() throws Exception {
final var storedRequest = mock(OAuth2Request);
final var principal = mock(Principal.class);
when(principal.getName()).thenReturn("user");
final var userAuthentication = mock(Authentication.class);
when(userAuthentication.getAuthorities()).thenReturn(Set.of(new SimpleGrantedAuthority("ROLE_USER"));
when(userAuthentication.getPrincipal()).thenReturn(principal);
final var oauth2Authentication = new OAuth2Authentication(storedRequest, authentication);
SecurityContextHolder.getContext().setAuthentication(oauth2Authentication);
// use MockMvc to test a @Controller or unit-test any other secured @Component as usual
}
解决方案 3 的使用示例
@Test
@WithMockAuthentication(authType = OAuth2Authentication.class, name = "user", authorities = "ROLE_USER")
public void test() throws Exception {
// use MockMvc to test a @Controller or unit-test any other secured @Component as usual
}
关于Spring Security 和 MockMvc - 需要模拟身份验证或主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55155021/