Sub topic 11
Testing Code That Depends on Generated APIs
This chapter assumes you can write Dart unit tests with flutter_test, and that you have a working Pigeon setup like the BatteryApi from the earlier chapters. You should also be comfortable with constructor injection. By the end you will be able to test Dart code that calls a generated API without a device. You will also know where each kind of test stops being useful.
What you are testing and where the seams are
Generated code is a thin layer, and Pigeon's own tests already cover it. Your tests should cover the code around it: the repository or controller that calls the API, how it handles errors, and the native implementation behind it.
A call from your app passes through several layers:
- Your Dart code, for example a repository or a view model.
- The generated Dart class, such as
BatteryApi. - The binary messenger, which carries encoded bytes.
- The generated Kotlin or Swift handler.
- Your native implementation, such as
BatteryApiImpl.
Each boundary between layers is a place to substitute a fake. Most of your tests will cut at the boundary between layers 1 and 2. A few will cut at layer 3. Native tests cut at layer 5.
| Seam | What runs for real | What is replaced | Best for |
|---|---|---|---|
| Fake generated class | Your Dart code | Everything from the generated class down | Logic and error handling in app code |
| Dart test harness | Your Dart code, the generated Dart class and the codec | The native side | Checking that arguments and results survive encoding |
| Native unit tests | Your Kotlin or Swift implementation | The Flutter engine and Dart | Platform logic |
Seam 1: inject the generated class and fake it
The generated Dart class is a normal class. Its constructor takes an optional BinaryMessenger, and it creates its own channels from the messenger and a name suffix. Nothing in it reads global state that you can't control, so the simplest approach is to accept it as a constructor parameter, with the real class as the default.
import 'package:flutter/services.dart';
import 'src/messages.g.dart';
class BatteryRepository {
BatteryRepository({BatteryApi? api}) : _api = api ?? BatteryApi();
final BatteryApi _api;
Future<String> describe() async {
try {
final info = await _api.getBatteryInfo();
if (info.state == BatteryState.unknown) {
return 'Battery ${info.level}%';
}
return 'Battery ${info.level}% (${info.state.name})';
} on PlatformException catch (e) {
return 'Battery unavailable: ${e.code}';
}
}
}The repository does two things worth testing: it formats a result, and it turns a PlatformException into a message. To test both, write a fake that extends the generated class.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:app/battery_repository.dart';
import 'package:app/src/messages.g.dart';
class FakeBatteryApi extends BatteryApi {
FakeBatteryApi(this._handler);
final Future<BatteryInfo> Function() _handler;
int calls = 0;
@override
Future<BatteryInfo> getBatteryInfo() {
calls++;
return _handler();
}
}
void main() {
test('formats level and state', () async {
final api = FakeBatteryApi(
() async => BatteryInfo(level: 80, state: BatteryState.charging),
);
final repo = BatteryRepository(api: api);
expect(await repo.describe(), 'Battery 80% (charging)');
expect(api.calls, 1);
});
test('omits the state when it is unknown', () async {
final repo = BatteryRepository(
api: FakeBatteryApi(
() async => BatteryInfo(level: 42, state: BatteryState.unknown),
),
);
expect(await repo.describe(), 'Battery 42%');
});
test('maps a PlatformException to a message', () async {
final repo = BatteryRepository(
api: FakeBatteryApi(
() async => throw PlatformException(code: 'no-battery'),
),
);
expect(await repo.describe(), 'Battery unavailable: no-battery');
});
}
</parameter>Replace app in the import paths with your package name.
Why the fake throws PlatformException
When native code reports an error, the generated Dart class throws a PlatformException with the code, message and details that native code supplied. Your fake should throw the same type so the code under test takes the same path as in production. A fake that throws a plain Exception tests a path that never happens. The error chapter covers how native code produces these values.
Keep the generated type out of your public surface
If many classes call BatteryApi, each test needs a fake of the generated class. A common design is a small interface that your app owns, with one adapter around the generated class.
abstract interface class BatteryService {
Future<int> level();
}
class PigeonBatteryService implements BatteryService {
PigeonBatteryService({BatteryApi? api}) : _api = api ?? BatteryApi();
final BatteryApi _api;
@override
Future<int> level() async => (await _api.getBatteryInfo()).level;
}The rest of the app depends on BatteryService, and tests write short fakes of that interface. The adapter is the only class that touches generated code. This also protects you when a regeneration changes a generated signature, because only the adapter has to change. The cost is one extra class per API, which isn't worth it for an API used in a single place.
Seam 2: the generated test harness
A fake at seam 1 never exercises the generated Dart code. If you want a test that sends a real call through the codec, ask Pigeon for a test harness. Add dartTestOut to the options in pigeons/messages.dart:
@ConfigurePigeon(PigeonOptions(
dartOut: 'lib/src/messages.g.dart',
dartTestOut: 'test/test_api.g.dart',
kotlinOut: 'android/app/src/main/kotlin/com/example/app/Messages.g.kt',
kotlinOptions: KotlinOptions(package: 'com.example.app'),
swiftOut: 'ios/Runner/Messages.g.swift',
))Run the generator again, as in the setup chapter. Pigeon writes a file that contains an abstract class for each @HostApi. In current versions the class name is TestHost followed by your API name, so TestHostBatteryApi. Check the generated file for the exact name in your version. The class has a static setUp method that registers your implementation as a mock handler on the test binary messenger.
import 'package:flutter_test/flutter_test.dart';
import 'package:app/battery_repository.dart';
import 'package:app/src/messages.g.dart';
import 'test_api.g.dart';
class FakeHost implements TestHostBatteryApi {
@override
BatteryInfo getBatteryInfo() =>
BatteryInfo(level: 55, state: BatteryState.discharging);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() => TestHostBatteryApi.setUp(FakeHost()));
tearDown(() => TestHostBatteryApi.setUp(null));
test('a real generated call round-trips through the codec', () async {
final repo = BatteryRepository();
expect(await repo.describe(), 'Battery 55% (discharging)');
});
}Here BatteryRepository() builds a real BatteryApi. Its call is encoded to bytes, delivered to the mock handler, decoded into arguments for FakeHost, and the result is encoded and decoded again on the way back. A mismatch between the schema and the codec would fail here, which a seam 1 test can't catch.
Notes on this approach:
TestWidgetsFlutterBinding.ensureInitialized()is required because the harness registers its handler on the test binding's messenger.- Always reset with
setUp(null)intearDown. The handler lives on a global messenger, so a leftover handler leaks into the next test. - The harness only covers
@HostApiinterfaces, which is the Dart-to-native direction. - Keep the test file under
test/and don't import it fromlib/. It depends onflutter_test, which is not a runtime dependency.
Testing the FlutterApi side
A @FlutterApi is an abstract Dart class that you implement. The listener you wrote in an earlier chapter is a plain class, so you can test it by calling its method directly.
import 'package:flutter_test/flutter_test.dart';
import 'package:app/src/messages.g.dart';
class RecordingListener extends BatteryEvents {
final List<int> levels = [];
@override
void onBatteryChanged(BatteryInfo info) => levels.add(info.level);
}
void main() {
test('records each reported level', () {
final listener = RecordingListener();
listener.onBatteryChanged(
BatteryInfo(level: 90, state: BatteryState.charging),
);
listener.onBatteryChanged(
BatteryInfo(level: 91, state: BatteryState.charging),
);
expect(listener.levels, [90, 91]);
});
}This checks your logic, not the wiring. The registration with BatteryEvents.setUp(...) is checked on a device or emulator, where native code actually sends a message.
Seam 3: test the native implementation directly
The Kotlin and Swift implementations are ordinary classes, so you can test them with JUnit and XCTest without starting Flutter. The constructor takes what the class needs, for instance a Context on Android, so you can pass a test double.
Design the implementation so that the platform call is isolated. For example, give BatteryApiImpl a small function or interface that reads the battery level. A unit test then supplies a fixed number, and you can check the mapping from the platform value to BatteryState and the behavior when the value is out of range.
Unit tests at this layer can't tell you that setUp was called with the right messenger. For that, use an integration test:
- Add
integration_testtodev_dependencies. - Write a test that calls the real generated Dart class.
- Run it on an emulator or device with
flutter test integration_test.
Keep this suite small. It is slower and flakier than the others, and it exists to prove the registration and the real platform behavior.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `MissingPluginException` or a hang in a seam 2 test | `TestHostBatteryApi.setUp` was never called, or `ensureInitialized` is missing | Register the fake in `setUp` and initialize the binding |
| A test passes alone and fails in the full run | A mock handler from an earlier test is still registered | Reset with `setUp(null)` in `tearDown` |
| `The non-abstract class ... is missing implementations` | The fake uses `implements` on the generated class | Use `extends` instead |
| Compile error in a fake after regeneration | The schema changed and the fake kept the old signature | Update the fake and the test, or add the adapter from above |
| Tests pass but the app crashes on device | Only seam 1 was used, so the codec and registration were never exercised | Add one seam 2 test and one integration test per API |
A practical test plan
For each API, a reasonable minimum is:
- Seam 1 tests for every branch in the code that calls the API, including each error code you handle.
- One seam 2 test per API method, to confirm that data classes and enums survive encoding. Include a case with a nullable field set to
null. - Native unit tests for any non-trivial mapping logic.
- One integration test per API on a real engine.
Exercise
A test of your repository passes with a fake that extends BatteryApi, but the app throws a type error on a real device when a nullable field comes back. Which seam would have caught this, and why did the first test miss it?
Show answer
Seam 2, the generated test harness (or an integration test). The fake at seam 1 replaces the generated class, so no value is ever encoded or decoded and the codec and schema are never exercised. The harness sends the call through the real generated Dart class and codec, so a mismatch between the schema and the data would fail in the test.
Exercise
Why must a seam 2 test call TestHostBatteryApi.setUp(null) in tearDown?
Show answer
The mock handler is registered on a global test binary messenger. If it isn't removed, a later test can reach the old fake instead of its own, which makes results depend on test order.