Sub topic 12
Testing code that uses channels
This chapter shows how to unit test Dart code that calls platform channels, without a device or emulator. It assumes you can write MethodChannel and EventChannel code (earlier chapters) and that you know flutter_test, setUp, and tearDown.
Why channel code needs a different test approach
A unit test runs on your development machine, in the Dart VM. No Kotlin or Swift code runs there, so no native handler answers the channel. If your test calls invokeMethod on a channel with nothing behind it, the call fails with a MissingPluginException.
The fix is to replace the native side with a mock handler written in Dart. The channel still sends a real message through the binary messenger, but the messenger hands it to your handler instead of to the platform. Everything on the Dart side runs for real: the codec, the argument encoding, and the error conversion.
Setting up a mock method handler
The test binding gives you a TestDefaultBinaryMessenger. It has a setMockMethodCallHandler method that takes the channel and a function from MethodCall to a result. Three rules apply:
- Call
TestWidgetsFlutterBinding.ensureInitialized()before you touch the messenger. - Register the handler in
setUp, so every test starts from a known state. - Remove the handler in
tearDownby passingnull. Otherwise one test's mock leaks into the next.
Here is a first test for the BatteryService from the method channel chapter. Replace my_app with your package name.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/battery_service.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('com.example.app/battery');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
tearDown(() {
messenger.setMockMethodCallHandler(channel, null);
});
test('returns the level reported by the platform', () async {
messenger.setMockMethodCallHandler(channel, (MethodCall call) async {
if (call.method == 'getBatteryLevel') return 42;
return null;
});
final level = await BatteryService().getBatteryLevel();
expect(level, 42);
});
}The channel name in the test must match the name in the service exactly. If you misspell it, the mock never sees the call and you get a MissingPluginException.
Testing the error paths
Success is the easy case. The code you most need to test is what happens when native code reports a failure. To simulate an result.error(...) from Kotlin or a FlutterError from Swift, throw a PlatformException from the mock handler. The test messenger encodes it as an error reply, and the channel decodes it again, exactly as it would for a real native error.
test('turns a native error into a StateError', () async {
messenger.setMockMethodCallHandler(channel, (MethodCall call) async {
throw PlatformException(
code: 'UNAVAILABLE',
message: 'Battery level not available.',
);
});
expect(
() => BatteryService().getBatteryLevel(),
throwsA(
isA<StateError>().having(
(e) => e.message,
'message',
contains('UNAVAILABLE'),
),
),
);
});Note that expect receives a closure, not an awaited call. That lets throwsA catch the error from the returned Future.
Simulating a missing method
Native code answers an unknown method with notImplemented (Kotlin) or FlutterMethodNotImplemented (Swift). Dart reports that as a MissingPluginException. To simulate it, throw MissingPluginException from the mock handler. The messenger turns it into the empty "not implemented" reply.
test('reports a method the platform does not implement', () async {
messenger.setMockMethodCallHandler(channel, (MethodCall call) async {
throw MissingPluginException();
});
expect(
() => channel.invokeMethod<int>('getBatteryLevel'),
throwsA(isA<MissingPluginException>()),
);
});You can also test the case where no handler is registered at all. That is what an app sees when a plugin was never linked into the build, or when a hot restart happens in a state the plugin does not handle.
Checking what Dart sent
A mock handler is also a place to record the calls it receives. This verifies method names and arguments, not only return values. It matters for methods that take parameters, where a typo in an argument key silently breaks the real native handler.
test('sends the expected method and arguments', () async {
final calls = <MethodCall>[];
messenger.setMockMethodCallHandler(channel, (MethodCall call) async {
calls.add(call);
return null;
});
await channel.invokeMethod<void>('setThreshold', {'percent': 20});
expect(calls, hasLength(1));
expect(calls.single.method, 'setThreshold');
expect(calls.single.arguments, {'percent': 20});
});The arguments reach the handler after a round trip through the standard codec. A Map<String, int> you send can arrive as a Map<Object?, Object?>. Comparing with equals or a map literal works, but a strict type check such as isA<Map<String, int>>() fails. This also shows you the same type loosening your Kotlin and Swift code will see.
Mocking an EventChannel
EventChannel has its own mock API: setMockStreamHandler. You pass a MockStreamHandler, which you usually build with MockStreamHandler.inline. It takes two callbacks that mirror the native StreamHandler:
onListen(arguments, events)runs when Dart starts listening. Use theeventssink to push data withsuccess,error, andendOfStream.onCancel(arguments)runs when Dart cancels the subscription.
This test covers the TickService from the event channel chapter:
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/tick_service.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const eventChannel = EventChannel('com.example.app/ticks');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
tearDown(() {
messenger.setMockStreamHandler(eventChannel, null);
});
test('emits the values sent by the platform, then completes', () {
messenger.setMockStreamHandler(
eventChannel,
MockStreamHandler.inline(
onListen: (Object? arguments, MockStreamHandlerEventSink events) {
events.success(0);
events.success(1);
events.success(2);
events.endOfStream();
},
),
);
expect(TickService().ticks, emitsInOrder([0, 1, 2, emitsDone]));
});
test('surfaces native errors as stream errors', () {
messenger.setMockStreamHandler(
eventChannel,
MockStreamHandler.inline(
onListen: (Object? arguments, MockStreamHandlerEventSink events) {
events.error(code: 'SENSOR_FAILED', message: 'Sensor stopped.');
},
),
);
expect(TickService().ticks, emitsError(isA<PlatformException>()));
});
test('tells the platform to stop when the subscription is cancelled',
() async {
var cancelled = false;
messenger.setMockStreamHandler(
eventChannel,
MockStreamHandler.inline(
onListen: (Object? arguments, MockStreamHandlerEventSink events) {
events.success(0);
},
onCancel: (Object? arguments) {
cancelled = true;
},
),
);
final first = Completer<int>();
final sub = TickService().ticks.listen(first.complete);
await first.future;
await sub.cancel();
expect(cancelled, isTrue);
});
}Add import 'dart:async'; at the top of the file for Completer.
The cancel test is the one that guards against the most common event channel bug, a native listener that keeps running after Dart stops listening. The unit test only checks that Dart sends the cancel message. Whether your Kotlin or Swift onCancel really stops the timer is a native question (see the next section).
What unit tests with mocks cannot prove
A mock handler checks your Dart code against the contract you wrote in the test. It cannot tell you that the real native side honors that contract. Three gaps remain:
- Name or method mismatches. The Dart service and the Kotlin handler can use different channel names or method strings. Both sides compile and both tests pass.
- Type mismatches. Your mock returns an
int, but the real handler returns aLongthat the codec turns into something you did not expect, or aDoublewhere Dart expects anint. - Native lifecycle bugs. A stream handler that leaks a timer, or a handler that replies twice, never shows up in a Dart VM test.
Cover these gaps in three layers:
| Layer | Tool | What it checks |
|---|---|---|
| Dart unit test | `flutter_test` and mock handlers | Dart logic, argument shape, error conversion |
| Native unit test | JUnit on Android, XCTest on iOS | Handler logic, `onListen` and `onCancel` cleanup |
| Integration test | `integration_test` on a device or emulator | The real channel, names, and types end to end |
To make native unit tests possible, keep the real work out of the channel callback. Put battery reading or timer logic in a small class that takes plain inputs and returns plain outputs. The setMethodCallHandler closure then only maps call.method to that class. You can test the class natively without a FlutterEngine.
Keeping channel code easy to test
Two design choices make all of the above simpler.
First, wrap each channel in one small service class, as BatteryService does. The rest of the app depends on the service, not on MethodChannel. Widget tests can then pass in a fake service, and only the service's own tests need channel mocks.
Second, let the service accept its channel as a constructor parameter with a default value. A test can then create a channel with a unique name or reuse one, and no global state is shared between tests.
import 'package:flutter/services.dart';
class BatteryService {
BatteryService({MethodChannel? channel})
: _channel = channel ?? const MethodChannel('com.example.app/battery');
final MethodChannel _channel;
Future<int?> getBatteryLevel() async {
try {
return await _channel.invokeMethod<int>('getBatteryLevel');
} on PlatformException catch (e) {
throw StateError('Battery unavailable: ${e.code} ${e.message}');
}
}
}Common mistakes
- Forgetting
ensureInitialized(). Without it, the binding is missing and the first access to the messenger throws. - Not clearing the handler. A mock left over from one test hides a
MissingPluginExceptionthat a later test should have seen. - Awaiting the wrong thing. For a stream, assert with
expect(stream, emitsInOrder(...)). Callingawait stream.firston a stream that never emits hangs until the test times out. - Using a different channel name in the test. The mock is keyed by name, so a typo gives you a
MissingPluginException, not a clear failure. - Treating a passing mock test as proof the native code works. It proves only the Dart half.
Exercise
A test registers a mock handler for MethodChannel('com.example.app/battery') and then calls BatteryService().getBatteryLevel(). The test fails with a MissingPluginException, although the handler returns 42. Name two likely causes.
Show answer
First, the channel name in the test differs from the one used by the service, so the mock is never reached. Second, the handler was registered after the call ran or was already removed in tearDown, or ensureInitialized() and the messenger were set up for a different binding. Check the exact name string and the order of setUp, the call, and tearDown.
Exercise
Write a test that proves TickService().ticks stops the native side after the first event. Which callback records the proof, and what must the test do before asserting?
Show answer
Use MockStreamHandler.inline with an onCancel callback that sets a cancelled flag. The test must listen to the stream, wait for the first event (for example with a Completer), then await sub.cancel(), and only then expect(cancelled, isTrue). Asserting before the cancel completes would race the flag.