MethodCall 列表在 Flutter 插件单元测试中的用途
Purpose of MethodCall list in Flutter plugin unit tests
创建插件时的默认单元测试设置如下所示:
void main() {
const MethodChannel channel = MethodChannel(
'com.example/my_plugin');
setUp(() {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return '42';
});
});
tearDown(() {
channel.setMockMethodCallHandler(null);
});
test('getPlatformVersion', () async {
expect(await MyPlugin.platformVersion, '42');
});
}
但是,在很多源代码中,我看到人们使用名为 log
的 List<MethodCall>
。这是一个 example:
test('setPreferredOrientations control test', () async {
final List<MethodCall> log = <MethodCall>[];
SystemChannels.platform.setMockMethodCallHandler((MethodCall methodCall) async {
log.add(methodCall);
});
await SystemChrome.setPreferredOrientations(<DeviceOrientation>[
DeviceOrientation.portraitUp,
]);
expect(log, hasLength(1));
expect(log.single, isMethodCall(
'SystemChrome.setPreferredOrientations',
arguments: <String>['DeviceOrientation.portraitUp'],
));
});
我理解 setMockMethodCallHandler
的模拟,但为什么要使用 MethodCall 列表,而你只能使用一个?如果只是一个案例我可能不会太在意,但我在源代码中一遍又一遍地看到这种模式。
我认为重点是验证方法调用处理程序是否恰好被触发一次(因此添加 ("logged") 正好是 List<MethodCall>
中的一个条目)。如果它只是一个从 null
变为非 null
的 MethodCall
变量,验证它没有被多次触发就没那么简单了。
创建插件时的默认单元测试设置如下所示:
void main() {
const MethodChannel channel = MethodChannel(
'com.example/my_plugin');
setUp(() {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return '42';
});
});
tearDown(() {
channel.setMockMethodCallHandler(null);
});
test('getPlatformVersion', () async {
expect(await MyPlugin.platformVersion, '42');
});
}
但是,在很多源代码中,我看到人们使用名为 log
的 List<MethodCall>
。这是一个 example:
test('setPreferredOrientations control test', () async {
final List<MethodCall> log = <MethodCall>[];
SystemChannels.platform.setMockMethodCallHandler((MethodCall methodCall) async {
log.add(methodCall);
});
await SystemChrome.setPreferredOrientations(<DeviceOrientation>[
DeviceOrientation.portraitUp,
]);
expect(log, hasLength(1));
expect(log.single, isMethodCall(
'SystemChrome.setPreferredOrientations',
arguments: <String>['DeviceOrientation.portraitUp'],
));
});
我理解 setMockMethodCallHandler
的模拟,但为什么要使用 MethodCall 列表,而你只能使用一个?如果只是一个案例我可能不会太在意,但我在源代码中一遍又一遍地看到这种模式。
我认为重点是验证方法调用处理程序是否恰好被触发一次(因此添加 ("logged") 正好是 List<MethodCall>
中的一个条目)。如果它只是一个从 null
变为非 null
的 MethodCall
变量,验证它没有被多次触发就没那么简单了。