【问题标题】:How to test ImagePicker in Flutter Driver?如何在 Flutter Driver 中测试 ImagePicker?
【发布时间】:2019-10-28 12:33:58
【问题描述】:

在 Flutter 集成测试中,我们如何处理 ImagePicker?以及其他平台相关的插件?

【问题讨论】:

    标签: flutter-test


    【解决方案1】:

    最后,我得到了这个问题的解决方案。 这是 app.dart 中的代码:

    在assets中准备一个图片文件,例如:images/sample.png。

    import 'dart:io';
    import 'dart:typed_data';
    import 'package:path_provider/path_provider.dart';
    
    import 'package:image_picker_test/main.dart' as app;
    import 'package:flutter_driver/driver_extension.dart';
    import 'package:flutter/services.dart';
    void main() {
      // This line enables the extension.
      enableFlutterDriverExtension();
    
      const MethodChannel channel =
      MethodChannel('plugins.flutter.io/image_picker');
    
      channel.setMockMethodCallHandler((MethodCall methodCall) async {
        ByteData data = await rootBundle.load('images/sample.png');
        Uint8List bytes = data.buffer.asUint8List();
        Directory tempDir = await getTemporaryDirectory();
        File file = await File('${tempDir.path}/tmp.tmp', ).writeAsBytes(bytes);
        print(file.path);
        return file.path;
      });
    
    
      app.main();
    }
    

    【讨论】:

    • 我不断收到关于未找到 dart:ui 的错误消息,它来自 path_provider。你能找到解决办法吗?
    • @jdixon04 Frank提供的这段代码sn-p必须在app.dart中,不能在某个测试文件中,否则会出现你描述的这种错误
    • 能否提供完整的sn-p代码,测试应用时如何调用该函数?
    • @Frank 你能附上你用来测试 ImagePicker 的 driver_test 代码吗?
    【解决方案2】:

    Frank Yan 的解决方案效果很好。基本上他使用 MethodChannel 作为 ImagePicker 请求的拦截器

    MethodChannel('plugins.flutter.io/image_picker')
    

    在这一部分中,他定义了必须模拟哪个插件

    channel.setMockMethodCallHandler((MethodCall methodCall) async {
        ByteData data = await rootBundle.load('images/sample.png');
        Uint8List bytes = data.buffer.asUint8List();
        Directory tempDir = await getTemporaryDirectory();
        File file = await File('${tempDir.path}/tmp.tmp', ).writeAsBytes(bytes);
        print(file.path);
        return file.path;
      });
    

    这个函数定义了从请求到图像选择器插件必须返回的内容。因此,每次用户使用图像选择器时,您的程序都会执行这些操作。在这里,它只会从“images/sample.png”返回图像。就我而言,我必须将图像放入项目根目录中的 assets/image.png 中。无论如何,您可以模拟任何这样的插件。我还必须模拟在图像选择器结束工作后调用的裁剪器插件。

    **注意:**mocking 不是 e2e 的最佳方式,也不是 Flutter 集成测试中调用的最佳方式。我使用它只是因为目前没有解决方法(我找不到它),并且在我的场景中我被图片上传的步骤所阻止。所以要小心使用这种方法。

    你不需要在测试的任何地方调用这个函数。您的应用将使用我们在 MethodChannel 构造函数 MethodChannel(''); 中定义的模拟插件运行;

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2019-04-23
      • 2021-03-26
      • 1970-01-01
      • 2022-07-18
      • 1970-01-01
      相关资源
      最近更新 更多