У меня есть следующий код в методе, который я пытаюсь протестировать в приложении SpringBoot.
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String token = (String)authentication.getCredentials();
Проблема в том, что объект authentication
всегда имеет значение null в режиме модульного теста.
Мой метод Test -
@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();
возвращает нулевое значение.
Я не уверен, что мне не хватает.