Flutter 小部件测试 Clipboard.setData 未来然后从未触发

Flutter widget test Clipboard.setData future then never triggered

我正在尝试在我的应用程序中测试剪贴板功能。当我按下一个按钮时,它应该将我的文本复制到剪贴板。当我尝试使用小部件测试来测试此功能时,返回的未来不会得到解决。有没有办法模拟 Clipboard.setData 方法?

由于我的原始代码非常大,所以我做了一个具有相同问题的可重现小部件测试。当我执行 expect() 时,boolean dataCopied 为 false。

testWidgets('test clipboard function', (WidgetTester tester) async {
    var dataCopied = false;
    await tester.pumpWidget(
      MaterialApp(
        home: Container(
          width: 10,
          height: 10,
          child: ElevatedButton(
            onPressed: (() {
              Clipboard.setData(ClipboardData(text: "test")).then((_) {
                dataCopied = true;
              });
            }),
            child: Text("Copy Text"),
          ),
        ),
      ),
    );

    await tester.tap(find.byType(ElevatedButton));
    expect(dataCopied, true);
  });

我找到了解决办法。我检查了 flutter 源代码,似乎剪贴板 class 使用 SystemChannels.platform 调用本机剪贴板功能。从另一个 post 我看到可以模拟频道

testWidgets('test clipboard function', (WidgetTester tester) async {
    var dataCopied = false;
    
    final List<MethodCall> log = <MethodCall>[];
    SystemChannels.platform.setMockMethodCallHandler((MethodCall methodCall) async {
      log.add(methodCall);
    });

    await tester.pumpWidget(
      MaterialApp(
        home: Container(
          width: 10,
          height: 10,
          child: ElevatedButton(
            onPressed: (() {
              Clipboard.setData(ClipboardData(text: "test")).then((_) {
                dataCopied = true;
              });
            }),
            child: Text("Copy Text"),
          ),
        ),
      ),
    );

    await tester.tap(find.byType(ElevatedButton));
    expect(dataCopied, true);
  });