Sub topic 10
Testing the Dart layer with a mocked channel
A plugin has two halves. The native half runs on Android or iOS, and the Dart half runs anywhere Dart runs. This chapter covers the Dart half. You will replace the native side of the channel with a fake handler, so flutter test can check your Dart API on your computer, with no emulator, simulator or device.
This chapter assumes you have the BatteryInfo class and BatteryInfoException from the earlier chapters. You should also know how async/await and package:flutter_test work.
What a mocked channel replaces
When Dart calls invokeMethod, the MethodChannel encodes the call and sends it to a binary messenger. In a running app, the messenger delivers the bytes to the Kotlin or Swift handler. In a test, you install a mock handler on the messenger. The handler receives the decoded MethodCall and returns a value, and the channel sends that value back to your Dart code as the result.
The mock sits below your Dart class. Your encoding, the channel name, the method string and the exception mapping all run for real. Only the native result is made up.
What these tests can and cannot prove
| Question | Answered by a mocked-channel test? |
|---|---|
| Does `getBatteryLevel` send the method name the native side expects? | Yes |
| Are arguments packed with the right keys? | Yes |
| Does a `PlatformException` become a `BatteryInfoException`? | Yes |
| Does the Kotlin code read the real battery? | No. Use the example app or an integration test. |
| Do the Kotlin and Swift sides use the same channel name? | No. You must check this by reading both files. |
The mock only proves that the Dart code matches the contract you wrote into the test. If the test says 'battery_info' and the Swift file says 'battery-info', the test still passes and the app fails.
A basic test
Put tests in test/battery_info_test.dart in the plugin root, not in example/. Run them with flutter test. The plugin package depends on Flutter, so dart test does not work here.
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');
final calls = <MethodCall>[];
TestDefaultBinaryMessenger get messenger =>
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
setUp(() {
calls.clear();
messenger.setMockMethodCallHandler(channel, (MethodCall call) async {
calls.add(call);
if (call.method == 'getBatteryLevel') {
return 42;
}
return null;
});
});
tearDown(() {
messenger.setMockMethodCallHandler(channel, null);
});
test('returns the level sent by the platform', () async {
expect(await BatteryInfo().getBatteryLevel(), 42);
});
test('sends exactly one getBatteryLevel call', () async {
await BatteryInfo().getBatteryLevel();
expect(calls, hasLength(1));
expect(calls.single.method, 'getBatteryLevel');
expect(calls.single.arguments, isNull);
});
}Three details matter here.
TestWidgetsFlutterBinding.ensureInitialized()must run before you touch the messenger. Without it,TestDefaultBinaryMessengerBinding.instanceis not set up.- The
callslist records everyMethodCall. Asserting onmethodandargumentsis how you check what Dart sent, which a return-value assertion cannot show. tearDownremoves the handler by passingnull. If you skip it, a handler from one test can leak into the next, which makes failures depend on test order.
Testing error paths
Error handling is where mocked tests earn their keep, because the real error paths are hard to trigger on a device. You cannot easily make a phone report an unavailable battery. In a mock, you throw a PlatformException yourself:
test('wraps PlatformException in BatteryInfoException', () async {
messenger.setMockMethodCallHandler(channel, (MethodCall call) async {
throw PlatformException(
code: 'UNAVAILABLE',
message: 'Battery level not available.',
);
});
expect(
() => BatteryInfo().getBatteryLevel(),
throwsA(
isA<BatteryInfoException>()
.having((e) => e.code, 'code', 'UNAVAILABLE')
.having((e) => e.message, 'message', 'Battery level not available.'),
),
);
});The channel turns the thrown exception into an error envelope, then back into a PlatformException on the caller's side, the same path a native result.error(...) takes. Your catch clause is therefore exercised for real.
The missing-handler case
A different failure arises when nobody answers. If no handler is installed, or the native side calls result.notImplemented() (or returns FlutterMethodNotImplemented on iOS), Dart throws a MissingPluginException. That is not a PlatformException, so the on PlatformException clause in BatteryInfo does not catch it. Test that behavior so you know what callers will see:
test('throws MissingPluginException when no handler answers', () async {
messenger.setMockMethodCallHandler(channel, null);
expect(
() => BatteryInfo().getBatteryLevel(),
throwsA(isA<MissingPluginException>()),
);
});This is the same exception users get when they run your plugin on a platform you did not implement, such as web or desktop. Decide whether to document that or to map it to your own exception, and let the test lock in the decision.
A null result
The sample getBatteryLevel uses level!. If the platform returns null, the bang operator throws a null-check error that has nothing to do with your exception type. You can test this by returning null from the mock. Seeing the failure in a test is usually a good reason to change the Dart code to throw a BatteryInfoException('NULL_RESULT', ...) instead.
Testing an EventChannel
Streams have their own mock. Assume you added the onBatteryLevelChanged getter from the spine to BatteryInfo, backed by EventChannel('battery_info/level_changes'). Use setMockStreamHandler with a MockStreamHandler:
import 'package:battery_info/battery_info.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const events = EventChannel('battery_info/level_changes');
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockStreamHandler(events, null);
});
test('emits levels pushed by the platform', () async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockStreamHandler(
events,
MockStreamHandler.inline(
onListen: (Object? arguments, MockStreamHandlerEventSink sink) {
sink.success(80);
sink.success(79);
sink.endOfStream();
},
),
);
expect(BatteryInfo().onBatteryLevelChanged, emitsInOrder([80, 79, emitsDone]));
});
}onListen runs when the first listener subscribes, which matches the real behavior of receiveBroadcastStream. Calling sink.error(code: 'X', message: 'm') lets you check that stream errors reach subscribers.
Common mistakes
- Wrong channel name in the test. The mock is keyed by the channel's name and codec. A typo means your mock never fires and you get
MissingPluginException. - Forgetting
awaiton an asyncexpect. WiththrowsA, pass a closure, as shown above, orexpectLaterwith a future. Otherwise the test can finish before the assertion runs. - Returning types the codec cannot carry. Standard codec values are
null, booleans, numbers, strings, byte and number lists, lists and maps. Returning a custom class from the mock fails to encode, which is also what would happen from real native code. - Sharing state between tests. Clear recorded calls in
setUp, and remove handlers intearDown.
Exercise
A test installs a mock handler for MethodChannel('battery_info') that returns 42, but BatteryInfo().getBatteryLevel() throws MissingPluginException. Name two likely causes.
Show answer
The handler may have been installed on a different channel name than the one the class uses (a typo), or it was removed before the call ran, for example by a tearDown that sets the handler to null, or the test never called TestWidgetsFlutterBinding.ensureInitialized() and set the handler on a different binding. A handler registered for another channel, or none at all, leaves the real channel unanswered.
Exercise
Write the mock handler body that makes getBatteryLevel fail with code UNAVAILABLE, and say which exception type the caller sees when the Dart class wraps platform errors.
Show answer
Throw PlatformException(code: 'UNAVAILABLE', message: 'Battery level not available.') inside the handler. The caller sees a BatteryInfoException with code equal to 'UNAVAILABLE', because the Dart class catches PlatformException and rethrows its own type.
Exercise
Why can a green mocked-channel test still ship a broken plugin?
Show answer
The mock replaces the native code, so the test only checks that Dart matches the contract written in the test. If the Kotlin or Swift side uses a different channel name, method string or argument key, the test still passes. Integration tests on a device, or a careful comparison of the three files, are needed to catch it.