Sub topic 10
Testing with mock initial values
This chapter shows how to unit test code that depends on flutter_secure_storage, without a device or emulator. It assumes you can write Dart tests with flutter_test, that you have the TokenRepository from the previous chapter, and that you know how async tests work.
Why secure storage needs special handling in tests
FlutterSecureStorage does not store anything itself. Each call goes through a platform channel to native code: the Keychain on iOS, Keystore-backed storage on Android. Under flutter test, your code runs on the host machine's Dart VM, and no native side exists.
If you call storage.read(key: 'x') in a plain unit test, the call fails with a MissingPluginException. The test fails before it reaches your own logic.
You have two ways to fix this:
- Replace the platform layer with an in-memory map, using the package's
setMockInitialValues. - Replace the whole
FlutterSecureStorageobject with a test double, which is what you do when you need to force failures.
Most tests use the first approach. The second covers the cases the first cannot express.
Using setMockInitialValues
FlutterSecureStorage.setMockInitialValues is a static method. It takes a Map<String, String> and installs an in-memory implementation as the package's platform layer. Every FlutterSecureStorage instance then reads and writes that map, including the const FlutterSecureStorage() your repository creates by default.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/token_repository.dart';
void main() {
test('reads the stored refresh token', () async {
FlutterSecureStorage.setMockInitialValues({'refresh_token': 'abc123'});
final repo = TokenRepository();
expect(await repo.readRefreshToken(), 'abc123');
});
}Replace my_app with your package name from pubspec.yaml.
The map you pass is the starting state of the fake storage. An empty map {} models a fresh install with no saved values.
Keep these points in mind:
- The mock is global. It replaces a static platform instance, so values written in one test are still there in the next test of the same file unless you reset them.
- Call
setMockInitialValuesinsetUp, or at the top of each test, so every test starts from known data. - Each call replaces the previous map. It does not merge into it.
- Keys and values must be
String. That matches the real API, so it also catches mistakes such as trying to store anint.
Resetting state in setUp
A setUp block keeps tests independent. This group tests a full write, read and clear cycle:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/token_repository.dart';
void main() {
late TokenRepository repo;
setUp(() {
FlutterSecureStorage.setMockInitialValues({});
repo = TokenRepository();
});
test('returns null when nothing is stored', () async {
expect(await repo.readRefreshToken(), isNull);
});
test('saves and reads a token', () async {
await repo.saveRefreshToken('abc123');
expect(await repo.readRefreshToken(), 'abc123');
});
test('clear removes the token', () async {
await repo.saveRefreshToken('abc123');
await repo.clear();
expect(await repo.readRefreshToken(), isNull);
});
}Without the setUp reset, the second test would leave abc123 in the map. The first test could then fail depending on execution order.
Checking what was written
Tests should often confirm that a value actually reached storage, not only that the repository returned it. Because the mock is a real map behind the real API, you can ask the storage directly:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/token_repository.dart';
void main() {
test('stores the token under refresh_token', () async {
FlutterSecureStorage.setMockInitialValues({});
const storage = FlutterSecureStorage();
final repo = TokenRepository(storage);
await repo.saveRefreshToken('abc123');
expect(await storage.readAll(), {'refresh_token': 'abc123'});
});
}This test locks in the storage key name. If someone renames _refreshKey, users would be silently signed out after an update, because the app would no longer find the old entry. A test that pins the key name catches that change.
Simulating failures with a test double
The map-based mock never fails. It cannot reproduce the PlatformException your repository handles when stored data is unreadable. To test that branch, inject a test double. This is why the repository accepts an optional FlutterSecureStorage in its constructor.
The example uses the mocktail package. Add it as a dev dependency:
flutter pub add --dev mocktailimport 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:my_app/token_repository.dart';
class MockSecureStorage extends Mock implements FlutterSecureStorage {}
void main() {
late MockSecureStorage storage;
late TokenRepository repo;
setUp(() {
storage = MockSecureStorage();
repo = TokenRepository(storage);
});
test('treats unreadable data as signed out and wipes it', () async {
when(() => storage.read(key: any(named: 'key')))
.thenThrow(PlatformException(code: 'decrypt_failed'));
when(() => storage.deleteAll()).thenAnswer((_) async {});
final token = await repo.readRefreshToken();
expect(token, isNull);
verify(() => storage.deleteAll()).called(1);
});
}The test checks two outcomes: the caller sees null, which means signed out, and the repository cleared the broken data so the failure does not repeat on every launch.
The PlatformException code in the test is made up. The real code varies by platform and package version, so your repository should not depend on a specific code.
What the mock does not cover
setMockInitialValues tests your logic. It does not test the platform behavior. The in-memory map ignores:
- Keychain accessibility settings such as
first_unlock. - Android Keystore key generation and any Android options you pass.
- Data surviving or not surviving a reinstall or a restored backup.
- Locked-device behavior, for example a background task reading a value before the first unlock.
A practical split looks like this:
| Test type | Tool | What it proves |
|---|---|---|
| Unit test | `setMockInitialValues` | Repository logic, key names, sign-out clears data |
| Unit test | Test double (`mocktail`) | Error branches such as `PlatformException` |
| Integration test | Real device or emulator | Platform options, reinstall and backup behavior |
Widget tests and app-level tests
Widget tests have the same problem as unit tests: no native side. If a widget or its controller reads a token during initState or a startup check, call setMockInitialValues before pumpWidget.
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('starts with an empty store', (tester) async {
FlutterSecureStorage.setMockInitialValues({});
await tester.pumpWidget(
MaterialApp(
home: FutureBuilder<String?>(
future: const FlutterSecureStorage().read(key: 'refresh_token'),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
return Text(snapshot.data == null ? 'signed out' : 'signed in');
},
),
),
);
await tester.pumpAndSettle();
expect(find.text('signed out'), findsOneWidget);
});
}In a real app, give widgets a repository through your dependency injection, and fake that repository in widget tests. A widget test usually does not need to know about secure storage at all.
Common mistakes
- Forgetting the mock. The test fails with
MissingPluginException. CallsetMockInitialValuesbefore the first storage call. - Calling it after creating the repository and reading. The mock replaces the platform layer, so call it before any read or write in that test.
- Relying on leftover state. Tests pass alone and fail together. Reset in
setUp. - Passing non-string values. The map type is
Map<String, String>. Store numbers as strings and parse them in your repository. - Asserting on an implementation detail. Prefer checking the repository's public behavior, and pin the key name only where changing it would break existing users.
Exercise
Your TokenRepository test passes when run alone but fails when the whole file runs. One test calls saveRefreshToken('abc123'), and another expects readRefreshToken() to return null. What is the cause, and how do you fix it?
Show answer
setMockInitialValues installs global state, so the value saved by the first test is still in the in-memory map when the second test runs. Call FlutterSecureStorage.setMockInitialValues({}) in setUp so each test starts with an empty store.
Exercise
Why can't setMockInitialValues test the branch of readRefreshToken that catches PlatformException, and what do you use instead?
Show answer
The in-memory mock behaves like a plain map and never throws a PlatformException. Inject a test double, for example a mocktail mock that implements FlutterSecureStorage, stub read to throw, and verify that the result is null and that deleteAll was called.
Exercise
Name two behaviors of secure storage that unit tests with setMockInitialValues cannot verify.
Show answer
Any two of: Keychain accessibility settings such as first_unlock, Android Keystore and encrypted preferences behavior, whether data survives a reinstall or restored backup, and access while the device is locked. Check these on real devices or emulators.