useMockStorage function
Installs an in-memory SharedPreferences store for tests.
Two reasons this has to be called, not skipped:
- There is no platform plugin in a test process. Calling
SharedPreferences.getInstance()without a mock store throwsMissingPluginException: No implementation found for method getAll. - The store is a static platform instance, so it leaks between tests.
A value written in one test is still readable in the next one. Calling
this in
setUpis what makes each test start from a known state.
It is the storage counterpart to useMockClient — same shape of seam, same place in your test setup:
setUp(() async {
useMockStorage();
await AppBinding.initServices();
});
Seed values to test a pre-existing state, e.g. a returning user who has already finished onboarding:
useMockStorage(values: {'onboarding_complete': true});
Deliberately not called from SharedPrefService.init(). That method is
production code, and mocking the store there would swap real device storage
for an empty in-memory map on every app launch — nothing would survive a
cold start.
Implementation
void useMockStorage({Map<String, Object> values = const <String, Object>{}}) {
// `setMockInitialValues` is annotated `@visibleForTesting`, which the
// analyzer enforces per-file rather than per-purpose — so shipping it inside
// a test-helper library still trips the lint. This one call site is exactly
// where it belongs, so the ignore stays scoped to it.
// ignore: invalid_use_of_visible_for_testing_member
SharedPreferences.setMockInitialValues(values);
}