
# Testing

`package:spring_boot_starter_flutter_security/testing.dart` re-exports the test helpers of `spring_security_core`: `withMockUser`, `withAuthentication` and `withAnonymousUser`. An app's tests need no other dependency. For widget tests, the beans of the package are replaced like any bean.

## Why

A test of a guarded service, a `PrincipalView` or a guarded screen needs a user, without a provider and a login window. The helpers run code as a user; bean overrides replace the platform parts (the secure storage, the window) that a test machine does not have.

## Example

```dart
import 'package:spring_boot_starter_flutter_security/testing.dart';
import 'package:test/test.dart';

void main() {
  test('an admin sees the orders', () async {
    await withMockUser(() async {
      expect(await orders.all(), isNotEmpty);
    }, roles: ['ADMIN']);
  });
}
```

## Fakes in widget tests

Every bean of the package backs off when the application declares one of its type, and `springBootTest(overrides:)` replaces them:

```dart
final app = springBootTest(
  springApplication,
  overrides: [
    BeanOverride<SecretStore>(InMemorySecretStore()),   // no Keychain on the test machine
    BeanOverride<OAuth2LoginService>(FakeLoginService()), // no provider
  ],
);
```

| Bean | Replace it with |
|---|---|
| `SecretStore` | `InMemorySecretStore` |
| `OAuth2LoginService` | A fake that puts a user into the `SecurityContextHolder` |
| `AuthorizationWindow` | A fake that answers with a redirect, to test the real login service against a fake provider |
| `DPoPKey` | A key made in Dart |

`PrincipalNotifier` follows the `SecurityContextHolder`, so `withMockUser` and a fake login both rebuild `PrincipalBuilder` and `PrincipalView`.

## In Spring (Java)

`spring-security-test`'s `@WithMockUser`.

## See also

- [Testing in spring_boot_starter_flutter](../spring-boot-starter-flutter/testing.md)
- [spring_boot_starter_test](../spring-boot-starter-test/index.md)
