У меня в контроллере есть следующий код:
Код: Выделить всё
@MessageMapping(MESSAGE_MAPPING)
public void sendVote(final RequestVoteDto vote, final Authentication authentication) {
final UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
voteService.createVote(vote, userDetails.getUsername());
}
Код: Выделить всё
@Test
@WithMockUser(username = "userTest")
@DisplayName("Send vote should be accessible for authorized user")
void testSendVote_shouldBeAccessibleForAuthorizedUser() throws Exception {
// test code here
}
Почему это происходит и как это исправить?
Я создал специальную аннотацию @WithCustomAuthenticationPrincipal:< /p>
Код: Выделить всё
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory {
@Override
public SecurityContext createSecurityContext(final WithCustomAuthenticationPrincipal customUser) {
final SecurityContext context = SecurityContextHolder.createEmptyContext();
final UserDetailsImpl userDetails = new UserDetailsImpl(
new User()
.setEmail(customUser.username())
.setPassword(customUser.password())
.setSecurityRole(customUser.role())
);
final UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
context.setAuthentication(authentication);
return context;
}
}
Код: Выделить всё
@Test
@WithCustomAuthenticationPrincipal(username = "user@example.com", password = "password", role = SecurityRole.ROLE_ADMIN)
void testAuthenticationIsNotNull() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
assertNotNull(authentication);
assertEquals("user@example.com", ((UserDetailsImpl) authentication.getPrincipal()).getUsername());
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... n-the-test
Мобильная версия