簡體   English   中英

如何在 Flutter Driver 中測試 ImagePicker?

[英]How to test ImagePicker in Flutter Driver?

在 Flutter 集成測試中,我們如何處理 ImagePicker? 以及其他平台相關的插件?

最后,我得到了這個問題的解決方案。 這是 app.dart 中的代碼:

在資產中准備一個圖像文件,例如: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();
}

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(''); 中定義的模擬插件運行;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM