gpt4 book ai didi

java - Spring 启动 WebMvcTest : How to test controller method with Authentication object parameter?

转载 作者:行者123 更新时间:2023-12-01 12:05:56 25 4
gpt4 key购买 nike

这是这个问题的延续
Spring WebMvcTest how to mock Authentication?
我正在尝试在 Spring-boot 中测试接收 Authentication 的 Controller 方法。对象作为参数。 Controller 是 RestController@CrossOrigin注解。该方法如下所示:

@GetMapping("/authentication")
public String testAuthentication(Authentication authentication) {
UserDetailsStub userDetailsStub = (UserDetailsStub) authentication.getPrincipal();
return userDetailsStub.getUsername();
}
如您所见,我从参数中从身份验证中获取了主体。
问题是,在我的 WebMvcTest 中测试用例我得到一个 NullPointerException因为在测试用例中, authentication似乎为空。我的问题是为什么?
我试过添加 given调用将返回自定义 UserDetails @PostConstruct 中的对象测试用例中的注释方法,但我仍然得到 NullPointerException .
我的测试用例如下所示:
@Import(SecurityConfiguration.class)
@RunWith(SpringRunner.class)
@WebMvcTest(PDPController.class)
@AutoConfigureMockMvc(addFilters = false)
public class PDPControllerTests {

@Autowired
private MockMvc mvc;

@MockBean(name = "userDetailsService")
private MyUserDetailsService userDetailsService;

//..

@PostConstruct
public void setup() {
given(userDetailsService.loadUserByUsername(anyString()))
.willReturn(new UserDetailsStub());
}

//..

@Test
@WithUserDetails(value = "username", userDetailsServiceBeanName = "userDetailsService")
public void testAuthentication() throws Exception {
mvc.perform(get("/pdps/authentication").secure(true)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}

}
为什么是 authentication在测试用例中为 null,即使我在 @PostConstruct 中提供它方法?
可以在此处找到具有重现错误的最少代码的 GitHub 项目。
https://github.com/Kars1090/SpringSecurityTest
谢谢!

最佳答案

克隆您的项目后,我已收到有效的 Authentication Controller 方法中的对象。基本上,您在测试中有两个主要问题:

  • 不必要的额外配置
  • 过滤器的错误模拟配置:JwtRequestFilter

  • 总之,变化如下:
    public class UserDetailsStub implements UserDetails {

    private String username;
    private String password;
    private Collection<? extends GrantedAuthority> authorities;

    public UserDetailsStub() {}

    public static UserDetailsStub of (User user) {
    UserDetailsStub userDetails = new UserDetailsStub();
    if (null != user) {
    userDetails.username = user.getUsername();
    userDetails.password = user.getPassword();
    userDetails.authorities = user.getAuthorities();
    }
    return userDetails;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
    }

    @Override
    public String getPassword() {
    return password;
    }

    @Override
    public String getUsername() {
    return username;
    }
    // Rest of the code is equal to your version
    您的 Controller 方法:
    @GetMapping("/authentication")
    public String testAuthentication(Authentication authentication) {
    UserDetailsStub userDetailsStub = UserDetailsStub.of((User)
    authentication.getPrincipal());
    return userDetailsStub.getUsername();
    }
    和测试:
    @WebMvcTest(value = PDPController.class)
    public class PDPControllerTests {

    @Autowired
    private MockMvc mvc;

    /** You have not to mock the filter because in that case Spring
    * won't know how to deal with it, when the list of them
    * should be managed.
    *
    * That is the reason why you had to include
    * @AutoConfigureMockMvc(addFilters = false), but that
    * is preciselly what was avoiding the creation of your
    * Authentication object, because your JwtRequestFilter
    * was not being executed.
    *
    * With the current code, your filter will be executed and
    * the Authentication object created.
    */
    //@MockBean
    //private JwtRequestFilter jwtRequestFilter;

    // What you have to mock are the classes the filter uses internally
    @MockBean
    private MyUserDetailsService userDetailsService;

    @MockBean
    private JwtService jwtService;

    @Test
    @WithMockUser
    public void test() throws Exception {
    mvc.perform(
    get("/pdps/authentication").secure(true)
    .contentType(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk());
    }
    }

    关于java - Spring 启动 WebMvcTest : How to test controller method with Authentication object parameter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63419621/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com