testing library
Helpers for tests of secured code: run a piece of code as a given user,
so @PreAuthorize and its siblings see that user.
Import it in tests only. Each helper opens its own security context
scope, so tests running at the same time do not see each other's user,
and the user is gone when the helper's Future completes.
import 'package:spring_security_core/testing.dart';
test('admins cancel any order', () async {
await withMockUser(() => orders.cancel(order), roles: ['ADMIN']);
});
test('users cannot cancel orders of others', () async {
await expectLater(
withMockUser(() => orders.cancel(othersOrder)),
throwsA(isA<AccessDeniedException>()),
);
});
Spring (Java): @WithMockUser, @WithAnonymousUser and
@WithSecurityContext annotations on test methods.
Functions
-
withAnonymousUser<
T> (FutureOr< T> body()) → Future<T> -
Runs
bodyas an anonymous user (anonymousUserwithROLE_ANONYMOUS), as the web starter sets for a request without a login, and returns its result. -
withAuthentication<
T> (FutureOr< T> body(), Authentication authentication) → Future<T> -
Runs
bodywithauthenticationas the current user and returns its result. -
withMockUser<
T> (FutureOr< T> body(), {String username = 'user', List<String> roles = const ['USER'], List<String> ? authorities}) → Future<T> -
Runs
bodyas a logged-in user and returns its result.