Sub topic 13
Testing code that uses storage
What this chapter assumes
You should already have written a shared_preferences helper, a Note model with toMap and fromMap, and a sqflite database with onCreate and onUpgrade. You should also know the basics of flutter_test: test, setUp, tearDown and expect. This chapter shows how to test that code without a phone, an emulator or leftover data from earlier runs.
Why storage code is hard to test
Storage code has three properties that make tests slow or unreliable.
- It talks to the platform.
shared_preferences,path_provider,sqfliteandflutter_secure_storagecall native code through platform channels. In a plainflutter testrun there is no native side, so the call throws aMissingPluginException. - It keeps state between runs. A row written by one test can change the result of the next one. A test that passes alone and fails in a suite usually has this problem.
- It is asynchronous. Forgetting an
awaitcan leave a test finishing before the write does, so the assertion checks stale data.
The fix is to decide what each test is about and use the cheapest tool that still tests it.
Choosing a test layer
| Layer | What it proves | Storage used | Speed |
|---|---|---|---|
| Controller or widget test | Your UI logic handles loaded data, empty data and errors | A fake repository in memory | Milliseconds |
| Preferences test | Keys, defaults and types are right | `setMockInitialValues` | Milliseconds |
| Repository or SQL test | Your queries and mapping work against real SQLite | In-memory SQLite on the host | Tens of milliseconds |
| Migration test | An old database upgrades without losing rows | SQLite file in a temporary directory | Tens of milliseconds |
| Integration test | The real plugins work on a real platform | The device's actual storage | Seconds |
Most tests should sit in the first four rows. Keep the integration layer small, because it is slow and needs a device.
Testing preferences with mock values
shared_preferences ships a test helper. SharedPreferences.setMockInitialValues replaces the platform channel with an in-memory map, so getInstance() works without a device. The tests below call loadDarkMode from the preferences example.
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('loads saved dark mode value', () async {
SharedPreferences.setMockInitialValues({'dark_mode': true});
expect(await loadDarkMode(), isTrue);
});
test('defaults to false when nothing is stored', () async {
SharedPreferences.setMockInitialValues({});
expect(await loadDarkMode(), isFalse);
});
}Call setMockInitialValues at the start of every test, even with an empty map. That gives each test a known starting state no matter which tests ran before it. To test a write, call saveDarkMode(true) and then read the value back through loadDarkMode(). Test the observable behaviour, not the internal map.
Testing logic through a fake repository
Most of your code should not know that SQLite exists. If a controller depends on an abstract NoteRepository, a test can pass in a simple in-memory implementation. The sections that follow assume this interface from the repository chapter.
abstract class NoteRepository {
Future<List<Note>> all();
Future<Note> add(Note note);
Future<void> remove(int id);
}
class InMemoryNoteRepository implements NoteRepository {
final List<Note> _notes = [];
int _nextId = 1;
@override
Future<List<Note>> all() async => List.unmodifiable(_notes);
@override
Future<Note> add(Note note) async {
final saved = Note(id: _nextId++, title: note.title, body: note.body);
_notes.add(saved);
return saved;
}
@override
Future<void> remove(int id) async {
_notes.removeWhere((n) => n.id == id);
}
}
class FailingNoteRepository extends InMemoryNoteRepository {
@override
Future<List<Note>> all() async => throw Exception('disk full');
}
class NotesController {
NotesController(this._repo);
final NoteRepository _repo;
List<Note> notes = [];
String? error;
Future<void> load() async {
try {
notes = await _repo.all();
error = null;
} catch (_) {
error = 'Could not load notes';
}
}
}The fake mimics the real contract: it assigns ids and remove deletes by id. The failing subclass lets you test the error branch, which is hard to trigger with a real database.
import 'package:flutter_test/flutter_test.dart';
void main() {
test('load shows saved notes', () async {
final repo = InMemoryNoteRepository();
await repo.add(const Note(title: 'milk'));
final controller = NotesController(repo);
await controller.load();
expect(controller.notes.single.title, 'milk');
expect(controller.error, isNull);
});
test('load reports an error when storage fails', () async {
final controller = NotesController(FailingNoteRepository());
await controller.load();
expect(controller.notes, isEmpty);
expect(controller.error, 'Could not load notes');
});
}A fake is only trustworthy if it behaves like the real repository. The next section runs the same expectations against real SQL so the two do not drift apart.
Testing real SQL with in-memory SQLite
To check your queries, you need a real SQLite engine. The sqflite_common_ffi package, added under dev_dependencies, runs SQLite on your development machine through FFI (Dart's foreign function interface). It needs a SQLite library available on the host. Setting databaseFactory redirects every openDatabase call to it. Opening the special path inMemoryDatabasePath creates a database that disappears when it is closed, so every test starts clean.
import 'package:flutter_test/flutter_test.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
// Replace with the file that holds Note, insertNote, searchNotes, deleteNote.
import 'package:notes_app/notes_db.dart';
void main() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
late Database db;
setUp(() async {
db = await openDatabase(
inMemoryDatabasePath,
version: 1,
onCreate: (db, version) => db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT)',
),
);
});
tearDown(() => db.close());
test('inserted note can be found by title', () async {
await insertNote(db, const Note(title: 'milk', body: '2 litres'));
final found = await searchNotes(db, 'milk');
expect(found.single.body, '2 litres');
expect(found.single.id, isNotNull);
});
test('search input is treated as data, not SQL', () async {
await insertNote(db, const Note(title: 'a'));
final found = await searchNotes(db, "a' OR '1'='1");
expect(found, isEmpty);
});
test('delete removes only the requested row', () async {
final keep = await insertNote(db, const Note(title: 'keep'));
final drop = await insertNote(db, const Note(title: 'drop'));
await deleteNote(db, drop);
final rows = await db.query('notes');
expect(rows.single['id'], keep);
});
}The second test is a useful security regression test. If someone later changes whereArgs to string interpolation, this test fails.
Testing a migration
A migration test needs a database that persists between two opens, so use a file in a temporary directory instead of memory. The test builds a version 1 database, closes it, then opens it again with the version 2 opener. To make that possible, the opener must accept a path. Keep the original openNotesDatabaseV2() as a thin wrapper.
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
Future<Database> openNotesDatabaseV2At(String path) {
return openDatabase(
path,
version: 2,
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT, '
'pinned INTEGER NOT NULL DEFAULT 0)',
);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 2) {
await db.execute(
'ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0',
);
}
},
);
}
void main() {
sqfliteFfiInit();
databaseFactory = databaseFactoryFfi;
test('upgrading from v1 keeps rows and adds pinned', () async {
final dir = Directory.systemTemp.createTempSync('notes_migration');
addTearDown(() => dir.deleteSync(recursive: true));
final path = join(dir.path, 'notes.db');
final v1 = await openDatabase(
path,
version: 1,
onCreate: (db, version) => db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT)',
),
);
await v1.insert('notes', {'title': 'old note'});
await v1.close();
final v2 = await openNotesDatabaseV2At(path);
final rows = await v2.query('notes');
await v2.close();
expect(rows.single['title'], 'old note');
expect(rows.single['pinned'], 0);
});
}The v1 schema is written out by hand in the test on purpose. It is a frozen copy of what real users have installed. If you reused your current onCreate, the test would never exercise onUpgrade. Add one such test for every released schema version you still support.
Secrets and directories
Plugins such as flutter_secure_storage and path_provider also fail in plain unit tests. Avoid mocking their channels one by one. Instead:
- Put the token calls behind a small
TokenStoreinterface withread,writeandclear. Test against an in-memory implementation, and use the real plugin only in the production implementation. - Pass a
Directoryinto your file-based repository instead of callinggetApplicationDocumentsDirectory()inside it. Tests can then passDirectory.systemTemp.createTempSync().
This is the same dependency-injection idea as the repository: the code under test receives its storage location and does not look it up.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `MissingPluginException` | A plugin ran in a plain test with no native side | Inject a fake, or use the mock or FFI helper for that plugin |
| `Binding has not yet been initialized` | A plugin call ran before the test binding existed | Call `TestWidgetsFlutterBinding.ensureInitialized()` first in `main` |
| A test passes alone and fails in the suite | State leaked from an earlier test | Reset in `setUp`, and use a fresh in-memory database for each test |
| `database is locked` or a file that cannot be deleted | A database was left open | Close it in `tearDown` |
| A fake passes while the real code fails | The fake does not match the real contract | Run the same expectations against both implementations |
| An assertion sees old data | A missing `await` | Await every storage call, and turn on the `unawaited_futures` lint |
What to leave to integration tests
Host-side tests cannot show that Android backup rules, iOS keychain behaviour or file permissions work. A few tests in the integration_test package that run on a device or emulator should cover one full round trip per storage type: write, restart the app object, read. Keep them few. They confirm that the plugins are wired up correctly, and the logic itself is already covered by the faster tests above.
Exercise
Your NotesController.load should show 'Could not load notes' when the database throws. Which test layer is the cheapest correct place to test this, and how do you cause the failure?
Show answer
Use a controller test with a fake repository. Pass FailingNoteRepository, whose all() throws, into NotesController, call load(), and expect error to equal 'Could not load notes' and notes to be empty. No database is involved, so the test runs in milliseconds and the failure is easy to trigger.
Exercise
You add a due_date TEXT column in version 3. Which tests do you add or change, and why must the version 2 schema in the migration test be written out by hand?
Show answer
Add a migration test that creates a version 2 database file (written out by hand), inserts a row, closes it, reopens it with the version 3 opener, and checks the old row is intact and due_date is null. Keep the version 1 to 2 test too, because users can still upgrade from version 1, and extend it to check that version 1 databases reach version 3. The old schema must be a frozen copy because reusing the current onCreate would build the new schema directly and never run onUpgrade.
Exercise
Why call SharedPreferences.setMockInitialValues({}) at the start of a test that expects the default value?
Show answer
Mock values can carry over from earlier tests in the same file. Setting an empty map gives the test a known empty starting state, so the default value is returned because nothing was stored and not because of what ran before.