withMockUser<T> function
Runs body as a logged-in user and returns its result.
The user is named username (user by default), with the password
password, and has the roles roles (USER by default, giving
ROLE_USER). Pass authorities instead to give full authority names
(SCOPE_read); then roles is ignored. The principal is a User, so
principal.username works in expressions.
Spring (Java): @WithMockUser(username = "ada", roles = "ADMIN").
Implementation
Future<T> withMockUser<T>(
FutureOr<T> Function() body, {
String username = 'user',
List<String> roles = const ['USER'],
List<String>? authorities,
}) {
final builder = User.withUsername(username).password('password');
final user = authorities == null
? builder.roles(roles).build()
: builder.authorityNames(authorities).build();
return withAuthentication(
body,
UsernamePasswordAuthenticationToken.authenticated(
user,
user.password,
user.authorities,
),
);
}