Sub topic 10
Testing with Mock Initial Values
Assume you know basic Dart, async/await, Flutter tests, and the TokenRepository wrapper from the previous chapter. This chapter shows how to test that wrapper without starting Android or iOS.
flutter_secure_storage normally communicates with native platform code through a platform channel. A platform channel is a bridge between Dart and the operating system. In a unit test, there is no real Keychain or Android Keystore. The package provides setMockInitialValues to replace that bridge with an in-memory map.
Set up a predictable test
Call FlutterSecureStorage.setMockInitialValues before the test creates or uses a storage instance. Pass a map containing the keys and values that should already exist.
The map is shared by the mocked platform channel. Reset it in setUp so that one test cannot affect another test.
The following file includes a small repository and tests its read, write, and delete behavior. In a real project, keep TokenRepository in your application library and import it into the test instead of defining it in the test file.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
class TokenRepository {
TokenRepository([FlutterSecureStorage? storage])
: _storage = storage ?? const FlutterSecureStorage();
static const _refreshKey = 'refresh_token';
final FlutterSecureStorage _storage;
Future<void> saveRefreshToken(String token) {
return _storage.write(key: _refreshKey, value: token);
}
Future<String?> readRefreshToken() {
return _storage.read(key: _refreshKey);
}
Future<void> clear() {
return _storage.delete(key: _refreshKey);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
FlutterSecureStorage.setMockInitialValues({});
});
test('reads an existing refresh token', () async {
FlutterSecureStorage.setMockInitialValues({
'refresh_token': 'abc123',
});
final repository = TokenRepository();
expect(await repository.readRefreshToken(), 'abc123');
});
test('saves and clears a refresh token', () async {
final repository = TokenRepository();
await repository.saveRefreshToken('new-token');
expect(await repository.readRefreshToken(), 'new-token');
await repository.clear();
expect(await repository.readRefreshToken(), isNull);
});
}expect compares the actual result with the expected result. isNull checks that a missing key returns null. The test does not inspect private fields or the package's internal map. It checks the repository's public behavior.
Test the boundary, not the package
Your tests should verify decisions made by your repository:
- The correct key is used.
- A token can be saved and read.
- Clearing removes the token.
- Missing data is represented as
null. - Sign-out does not leave the refresh token behind.
Do not test that flutter_secure_storage itself correctly calls the operating system. That behavior belongs to the package's maintainers and requires platform integration testing.
| Test layer | What it checks | Typical environment |
|---|---|---|
| Repository unit test | Your key names and application behavior | Dart or Flutter test runner |
| Plugin integration test | Native Keychain or Keystore behavior | Android or iOS device |
| End-to-end test | Login and sign-out flows | Complete app |
The constructor accepts an optional FlutterSecureStorage, which keeps the repository replaceable in more advanced tests. The built-in mock is useful when you want to exercise the actual package API while avoiding native dependencies.
Common testing errors
A test may fail because the mock was initialized after the repository performed its first operation. Initialize it before reading or writing.
Another common error is shared state. If one test writes a token and the next test expects no token, reset the mock map in setUp.
Finally, test error handling separately if your repository catches PlatformException. A successful mock read does not prove that your application handles corrupted backups, unavailable secure hardware, or native configuration errors.
Exercise
Why should each test call setMockInitialValues with a fresh map?
Show answer
The mocked storage is shared state. Resetting it prevents writes from one test changing the starting conditions of another test.