Sub topic 10
Testing the Dart Layer with a Mocked Channel
This chapter assumes that you can write Dart tests, understand Future and async code, and have already created the BatteryInfo Dart API. The tests here do not require an Android device, an iPhone, or the native implementations.
Why mock the platform channel?
A plugin's Dart API communicates with Kotlin or Swift through a platform channel. A unit test can replace the native side with a mock handler. The handler receives the same method calls that native code would receive and returns a controlled value or error.
This keeps the test focused on Dart behavior:
- Does the API call the correct method?
- Does it convert the returned value to the expected type?
- Does it wrap a
PlatformExceptioninBatteryInfoException? - Does each test remove its mock handler afterward?
| Test case | Mock channel response | Dart assertion |
|---|---|---|
| Successful battery query | `42` | The method returns `42` |
| Native failure | `PlatformException` | The API throws `BatteryInfoException` |
Connect a mock to the channel
Flutter tests use a test binary messenger to intercept messages sent through MethodChannel. Initialize the test binding before installing a handler.
import 'package:battery_info/battery_info.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('battery_info');
setUp(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall call) async {
if (call.method == 'getBatteryLevel') {
return 42;
}
return null;
});
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null);
});
test('getBatteryLevel returns the value from the platform', () async {
expect(await BatteryInfo().getBatteryLevel(), 42);
});
test('getBatteryLevel wraps a native error', () async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (MethodCall call) async {
throw PlatformException(
code: 'UNAVAILABLE',
message: 'Battery level not available.',
);
});
await expectLater(
BatteryInfo().getBatteryLevel(),
throwsA(
predicate(
(Object error) =>
error is BatteryInfoException &&
error.code == 'UNAVAILABLE',
),
),
);
});
}The channel name must match the name in the production code exactly. The method name must also match the string sent by invokeMethod. A mismatch can make a test pass for the wrong reason if the mock returns a value without checking the call.
setUp runs before each test. tearDown clears the handler after each test, preventing one test's mock from affecting another test. The second test replaces the default success handler with one that throws a PlatformException, which verifies the Dart error-conversion path.
Understand the message flow
Run the test from the plugin package directory:
flutter testExercise
Exercise
Why should a test remove its mock method-call handler in tearDown?
Show answer
To isolate tests so that a handler installed by one test cannot intercept calls made by a later test.