首页 > 解决方案 > SecurityContextHolder 在单元测试期间返回一个 null Authentication 对象

问题描述

我尝试在 SpringBoot 应用程序中测试的方法中有以下代码。

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();  
String token = (String)authentication.getCredentials();

问题是该authentication对象在单元测试模式下始终为空。

我的测试方法是

@Test
public void testMyMethod() {
    // .. prepare other responses
    Authentication authentication = mock(Authentication.class);
    SecurityContext securityContext = mock(SecurityContext.class);
    when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    when(SecurityContextHolder.getContext().getAuthentication().getCredentials()).thenReturn("a_toke");

    String uri = baseuri + "/myapp";
    this.mockMvc.perform(post(uri).contentType(MediaType.APPLICATION_JSON).content(sampleRequestWithOneResource))
            .andExpect(status().isOk()).andExpect(MockMvcResultMatchers.jsonPath("$.status").value("SUCCESS"));

}

上面的 POST 调用导致执行需要从Authentication对象中读取令牌的代码。测试失败,因为SecurityContextHolder.getContext().getAuthentication();返回空值。

我不确定我错过了什么。

标签: spring-test

解决方案


推荐阅读