我在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();
返回空值,测试失败。
我不确定我错过了什么。