-
I stumbled upon the issue that I have a class implementing |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
@ancavar I had missed this question, sorry. Unfortunately, All you can do is:
@Test
@WithMockAuthentication(authType = UsernamePasswordAuthenticationToken.class, principalType = UserDetails.class, authorities = "ROLE_AUTHORIZED_PERSONNEL", name = "Ch4mp")
void givenUserIsAuthenticatedWithMockedAuthenticationAndGrantedWithAuthorizedPersonnel_whenGetSecret_thenReturnsSecret() {
final var userDetails = defaultUserDetails();
...
}
private UserDetails defaultUserDetails() {
// This cast is safe if you used "principalType = UserDetails.class" in test annotation
final var userDetails = (UserDetails) TestSecurityContextHolder.getContext().getAuthentication().getPrincipal();
when(userDetails.getAuthorities()).thenReturn((Collection) TestSecurityContextHolder.getContext().getAuthentication().getAuthorities());
when(userDetails.getUsername()).thenReturn(TestSecurityContextHolder.getContext().getAuthentication().getName());
when(userDetails.isAccountNonExpired()).thenReturn(true);
when(userDetails.isAccountNonLocked()).thenReturn(true);
when(userDetails.isCredentialsNonExpired()).thenReturn(true);
when(userDetails.isEnabled()).thenReturn(true);
return userDetails;
} As I don't know the type of In the case where you would actually be using |
Beta Was this translation helpful? Give feedback.
@ancavar I had missed this question, sorry.
Unfortunately,
Authentication#principal
is anObject
, so, there is no easy way I know to configure it with test annotations.All you can do is:
@WithMockUser
,@WithJwt
,@WithOpaqueToken
,@WithOAuth2Login
or@WithOidcLogin
)@WithMockAuthentication
and hand-configure theAuthentication
mock with something like that: