spring-test - 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();
返回空值。
我不确定我错过了什么。
解决方案
推荐阅读
- java - ExceptionHandler 在使用 @Order 和 LOWEST_PRECEDENCE 时捕获 AccessDeniedException?
- php - 想在 laravel 中实现 SOAP API(服务器)
- mysql - 根据按日期字段分组获取数据
- optimization - 何时必须/应该在 VHDL 中使用 range 关键字声明变量?
- bittorrent - DHT InfoHash 查找序列。PeerID 与 InfoHash
- windows - 查看所有登录到 Windows 10 计算机的用户
- python - 无法在 Python 中创建超过 2 个 txt.files
- javascript - 底部的 HTML 图像想要顶部
- ldap - Gerrit + LDAP:“无法将用户名“X”分配给帐户 Y;名称不符合“
- apache-spark - 小内存工作节点和性能