Spring Security和MockMvc - 需要模拟身份验证或委托人

问题描述 投票:0回答:1

我正在使用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)

我应该如何使用当前身份验证传递或模拟用户?谢谢。

spring spring-security spring-security-oauth2 mockmvc
1个回答
0
投票

NullPointerException即将到来,因为你的测试无法为OAuth2Authentication对象找到任何东西。您可以在测试用例中执行两项操作:

  1. 尝试在某些setUp方法中模拟OAuth2Authentication

要么

  1. 如果您使用的是Spring 4.0+,最好的解决方案是使用@WithMockUser注释测试方法 @Test @WithMockUser(username = "user1", password = "pwd", roles = "USER") public void mytest1() throws Exception { //Your test scenario }
© www.soinside.com 2019 - 2024. All rights reserved.