0

我已经在我的应用程序中使用了 file_picker,现在我创建了一个集成测试。我一直在寻找一种模拟 file_picker 或依赖项的方法,结果如下:

import 'dart:io';
import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path_provider/path_provider.dart';

void main() async {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  setUp(() {
    mockFilePicker();
  });

  testWidgets("test", (WidgetTester tester) async {
    // await app.main();
    // .. test case ..
  });
}

mockFilePicker() {
  const MethodChannel channel =
      MethodChannel('miguelruivo.flutter.plugins.filepicker');
  channel.setMockMethodCallHandler((MethodCall methodCall) async {
    print("MockMethodChannel run");

    ByteData data = await rootBundle.load('assets/images/ic_bill.png');
    Uint8List bytes = data.buffer.asUint8List();
    Directory tempDir = await getTemporaryDirectory();
    File file = await File(
      '${tempDir.path}/image.png',
    ).writeAsBytes(bytes);

    PlatformFile platformFile = PlatformFile(
        name: "image.png", size: file.lengthSync(), path: file.path);
    FilePickerResult filePickerResult = FilePickerResult([platformFile]);
    return filePickerResult;
  });
}

使用该代码,我收到如下错误:

[MethodChannelFilePicker] 平台异常:PlatformException(错误,无效参数:'FilePickerResult' 的实例,null,null)

如何解决这个问题?

4

1 回答 1

0

看起来通道方法调用需要一个地图列表而不是 FilePickerResult 对象。地图的格式为:

{
  'name': String,
  'path': String,
  'bytes': Uint8List,
  'size': int,
}

以下模拟频道对我有用:

  const MethodChannel channelFilePicker =
      MethodChannel('miguelruivo.flutter.plugins.filepicker');

  TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
      .setMockMethodCallHandler(channelFilePicker,
          (MethodCall methodCall) async {
    final ByteData data = await rootBundle.load('assets/icon/Icon.png');
    final Uint8List bytes = data.buffer.asUint8List();
    final Directory tempDir = await getTemporaryDirectory();
    final File file = await File(
      '${tempDir.path}/tmp.tmp',
    ).writeAsBytes(bytes);
    print(file.path);
    return [
      {
        'name': "Icon.png",
        'path': file.path,
        'bytes': bytes,
        'size': bytes.lengthInBytes,
      }
    ];
  });
于 2022-02-16T22:59:09.413 回答