Sub topic 16
Testing queries against an in-memory database
This chapter assumes you have the AppDatabase class from the earlier chapters, including the addItem, allItems, updateItem, deleteDone and watchOpenItems methods. You should also know setUp and tearDown in package:flutter_test, and how to read a Dart Stream.
Why an in-memory database
A database test should exercise the real SQL that drift generates. Mocking the database class tests your mock, not your queries. A file-based test database is slow to set up and can leak state between tests.
SQLite can keep a whole database in RAM. drift exposes this as NativeDatabase.memory(). Each call creates a new, empty database that disappears when it is closed. That gives you real SQLite behavior (constraints, ordering, defaults) with no files to clean up.
| Approach | Tests real SQL | Isolated per test | Speed |
|---|---|---|---|
| Mock the database class | No | Yes | Fastest |
| File-based test database | Yes | Only if you delete the file | Slow |
| `NativeDatabase.memory()` | Yes | Yes | Fast |
This works because the AppDatabase constructor from the earlier chapter accepts an optional QueryExecutor. Production code passes nothing and gets driftDatabase(name: 'app'). Tests pass an in-memory executor.
Setup
NativeDatabase lives in package:drift/native.dart, which is part of the drift package you already depend on. Tests that run on your development machine (flutter test) need a SQLite library available to the host. On Linux this is often the libsqlite3 package. macOS ships with one. If a test fails with an error about loading the sqlite3 library, install SQLite on the host first.
This chapter also uses StreamQueue for stream tests. Add the async package as a dev dependency:
flutter pub add dev:asyncA first test
Create test/database_test.dart. Replace todo_app with your own package name.
import 'package:drift/drift.dart' show InvalidDataException;
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:todo_app/database.dart';
void main() {
late AppDatabase db;
setUp(() {
db = AppDatabase(NativeDatabase.memory());
});
tearDown(() async {
await db.close();
});
test('inserted items can be read back', () async {
await db.addItem('Write tests');
final items = await db.allItems();
expect(items.single.title, 'Write tests');
expect(items.single.isDone, isFalse);
});
test('deleteDone removes only completed items', () async {
await db.addItem('Keep me');
await db.addItem('Finish me');
final all = await db.allItems();
final finish = all.firstWhere((i) => i.title == 'Finish me');
await db.updateItem(finish.copyWith(isDone: true));
final deleted = await db.deleteDone();
expect(deleted, 1);
final remaining = await db.allItems();
expect(remaining.map((i) => i.title), ['Keep me']);
});
test('an empty title is rejected', () async {
expect(
() => db.addItem(''),
throwsA(isA<InvalidDataException>()),
);
});
}Three details matter here.
setUpruns before every test, so each test gets its own empty database. Tests cannot affect each other, and they can run in any order.tearDowncloses the database. Skipping this leaves connections and timers open.- The third test checks the
withLength(min: 1, max: 100)rule from the table definition. drift validates this in Dart when you insert, and it throwsInvalidDataException. Testing a rule like this documents it and catches changes to the schema.
Testing streams
A watch() query emits its current result when you listen, then emits again after each change to the underlying table. The risk in testing is timing. If you write a row before the first result arrives, the first emission might already contain the row, and your assertion on the empty state fails.
StreamQueue removes that ambiguity. It lets you pull emissions one at a time and wait for each:
import 'package:async/async.dart';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:todo_app/database.dart';
void main() {
late AppDatabase db;
setUp(() {
db = AppDatabase(NativeDatabase.memory());
});
tearDown(() async {
await db.close();
});
test('watchOpenItems follows inserts and completions', () async {
final queue = StreamQueue(db.watchOpenItems());
expect(await queue.next, isEmpty);
await db.addItem('Write tests');
final afterInsert = await queue.next;
expect(afterInsert.single.title, 'Write tests');
await db.updateItem(afterInsert.single.copyWith(isDone: true));
expect(await queue.next, isEmpty);
await queue.cancel();
});
}Each await queue.next waits for the next emission, so the test reads top to bottom as the story of the stream. Cancel the queue at the end so the stream subscription does not outlive the test.
Seeding data with a helper
When many tests need the same starting rows, put the setup in a small function instead of repeating inserts:
Future<void> seed(AppDatabase db) async {
await db.addItem('Buy milk');
await db.addItem('Call dentist');
await db.addItem('Read chapter');
}Call it at the start of the tests that need it. Keeping seeding out of setUp means tests about the empty state stay simple.
What to test and what to leave out
Good candidates for database tests:
- Filters and ordering: that
watchOpenItemshides completed items and sorts newest first. - Update and delete scope: that a
whereclause touches only the rows you expect, as in thedeleteDonetest. - Defaults and constraints: that
isDonestarts false, and that invalid input is rejected. - Transactions: that a failing step rolls back earlier writes in the same transaction.
- Joins: that a to-do without a category still appears, with a
nullcategory, in a left outer join.
Poor candidates are the generated classes themselves. TodoItemsCompanion and copyWith are produced by drift and tested by its authors. Test your queries and your rules.
Limits of in-memory tests
An in-memory database runs the same SQLite engine as production, but it has no history. That makes it a poor fit for migration testing, because a fresh database always starts at the newest schema. To check that onUpgrade preserves user data, you need a database created at an older version and then upgraded. drift ships schema export and verification tooling in drift_dev for this purpose. Set it up once you have shipped a second schema version.
Common errors
- Library load failure on the host. The test cannot find SQLite. Install it on the development machine or CI image.
- Flaky stream assertions. You are using
await Future.delayed(...)to wait for emissions. UseStreamQueueandawait queue.nextinstead. - State bleeding between tests. The database is created outside
setUp, or never closed. - Hanging test runner. A stream subscription was never cancelled, or
db.close()was skipped.
Exercise
Write a test that verifies watchOpenItems returns the newest item first. Which StreamQueue calls do you need, and why not use Future.delayed between the inserts and the assertion?
Show answer
Create the database in setUp, then open final queue = StreamQueue(db.watchOpenItems()); and check await queue.next is empty. Insert 'first', await queue.next, then insert 'second' and await queue.next again. Assert the last list's titles equal ['second', 'first'], then call await queue.cancel(). Because createdAt defaults to the current time, a very fast second insert can get the same timestamp, so add a short delay between the two inserts or set createdAt explicitly in the companion. await queue.next waits for the actual emission, so the test is deterministic. A fixed Future.delayed guesses at timing and is either too slow or sometimes too short.
Exercise
Why does each test create its own NativeDatabase.memory() instead of reusing one database, and what happens to the data when db.close() runs?
Show answer
Each NativeDatabase.memory() call creates a separate empty database, so tests cannot see each other's rows and can run in any order. When the database is closed, the in-memory data is discarded, so no cleanup of files or tables is needed.