简体   繁体   English

Flutter插件单元测试中MethodCall列表的用途

[英]Purpose of MethodCall list in Flutter plugin unit tests

The default unit test setup when you create a plugin looks like this: 创建插件时的默认单元测试设置如下所示:

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');
  });
}

However, in a lot of the source code I see people using a List<MethodCall> called log . 但是,在许多源代码中,我看到人们使用称为logList<MethodCall> Here is an 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'],
    ));
  });

I understand the mocking with setMockMethodCallHandler , but why use a list of MethodCall when you could just use one? 我了解使用setMockMethodCallHandler ,但是为什么只使用一个时可以使用MethodCall列表呢? If it were just one case I wouldn't may much attention, but I see the pattern over and over in the source code. 如果只是一种情况,我可能不会特别注意,但是我在源代码中一遍又一遍地看到了这种模式。

I believe the point is to verify that the method call handler was triggered exactly once (and therefore added ("logged") exactly one entry into the List<MethodCall> ). 我认为关键是要验证方法调用处理程序是否仅被触发一次(并因此被正确地添加(“记录”)到List<MethodCall>一个条目)。 If it were simply a MethodCall variable that changed from null to non- null , verifying that it was not triggered multiple times would be less straightforward. 如果只是一个从null变为non- nullMethodCall变量,那么验证它没有被多次触发将不那么直接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM