flutter - 在 Flutter 上模拟 getExternalStorageDirectory

标签 flutter dart mobile mocking

我正在尝试模拟函数 getExternalStorageDirectory,但总是返回错误:
“UnsupportedError(不支持的操作:功能仅在 Android 上可用)”
我正在使用 setMockMethodCallHandler 方法来模拟它,但是在调用该方法之前发生了错误。
测试方法

    test('empty listReportModel', () async {
      
      TestWidgetsFlutterBinding.ensureInitialized();
      final directory = await Directory.systemTemp.createTemp();
      const MethodChannel channel =
          MethodChannel('plugins.flutter.io/path_provider');
      channel.setMockMethodCallHandler((MethodCall methodCall) async {
        if (methodCall.method == 'getExternalStorageDirectory') {
          return directory.path;
        }
        return ".";
      });

      when(Modular.get<IDailyGainsController>().listDailyGains())
          .thenAnswer((_) => Future.value(listDailyGainsModel));

      when(Modular.get<IReportsController>().listReports())
          .thenAnswer((_) => Future.value(new List<ReportsModel>()));

      var configurationController = Modular.get<IConfigurationController>();

      var response = await configurationController.createBackup();

      expect(response.filePath, null);
    });
方法
  Future<CreateBackupResponse> createBackup() async {
    CreateBackupResponse response = new CreateBackupResponse();

    var dailyGains = await exportDailyGainsToCSV();
    var reports = await exportReportsToCSV();

    final Directory directory = await getApplicationDocumentsDirectory();
    final Directory externalDirectory = await getExternalStorageDirectory();

    if (dailyGains.filePath != null && reports.filePath != null) {
      File dailyGainsFile = File(dailyGains.filePath);
      File reportsFile = File(reports.filePath);

      var encoder = ZipFileEncoder();
      encoder.create(externalDirectory.path + "/" + 'backup.zip');
      encoder.addFile(dailyGainsFile);
      encoder.addFile(reportsFile);
      encoder.close();

      await _removeFile(dailyGainsFile.path);
      await _removeFile(reportsFile.path);

      response.filePath = directory.path + "/" + 'backup.zip';
    }

    return response;
  }

最佳答案

pub.dev说:

path_provider now uses a PlatformInterface, meaning that not all platforms share the a single PlatformChannel-based implementation. With that change, tests should be updated to mock PathProviderPlatform rather than PlatformChannel.


这意味着在您的测试目录中的某处创建以下模拟类:
import 'package:mockito/mockito.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';

const String kTemporaryPath = 'temporaryPath';
const String kApplicationSupportPath = 'applicationSupportPath';
const String kDownloadsPath = 'downloadsPath';
const String kLibraryPath = 'libraryPath';
const String kApplicationDocumentsPath = 'applicationDocumentsPath';
const String kExternalCachePath = 'externalCachePath';
const String kExternalStoragePath = 'externalStoragePath';

class MockPathProviderPlatform extends Mock
    with MockPlatformInterfaceMixin
    implements PathProviderPlatform {
  Future<String> getTemporaryPath() async {
    return kTemporaryPath;
  }

  Future<String> getApplicationSupportPath() async {
    return kApplicationSupportPath;
  }

  Future<String> getLibraryPath() async {
    return kLibraryPath;
  }

  Future<String> getApplicationDocumentsPath() async {
    return kApplicationDocumentsPath;
  }

  Future<String> getExternalStoragePath() async {
    return kExternalStoragePath;
  }

  Future<List<String>> getExternalCachePaths() async {
    return <String>[kExternalCachePath];
  }

  Future<List<String>> getExternalStoragePaths({
    StorageDirectory type,
  }) async {
    return <String>[kExternalStoragePath];
  }

  Future<String> getDownloadsPath() async {
    return kDownloadsPath;
  }
}
并通过以下方式构建您的测试:
void main() {
  group('PathProvider', () {
    TestWidgetsFlutterBinding.ensureInitialized();

    setUp(() async {
      PathProviderPlatform.instance = MockPathProviderPlatform();
      // This is required because we manually register the Linux path provider when on the Linux platform.
      // Will be removed when automatic registration of dart plugins is implemented.
      // See this issue https://github.com/flutter/flutter/issues/52267 for details
      disablePathProviderPlatformOverride = true;
    });

    test('getTemporaryDirectory', () async {
      Directory result = await getTemporaryDirectory();
      expect(result.path, kTemporaryPath);
    });
  } 
}
Here您可以查看完整的示例。

关于flutter - 在 Flutter 上模拟 getExternalStorageDirectory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62597011/

相关文章:

image - flutter : The argument type 'Image' can't be assigned to the parameter type 'IconData'

android - 一次性读取Firebase云( Dart/flutter )

html - 以移动设备为中心的 Div

android - Flutter 拨动开关和共享首选项

Flutter Push 通知未在 IOS 上显示

android - TextEditingController 使小部件失去其先前的状态

dart - 如何抑制 "missing concrete implementation"警告?

html - 使用内联样式为移动设备格式化文本宽度

html - Bootstrap 渲染在移动设备上变窄

flutter - 如何在启用 nullsafety 的情况下从 swagger json 生成 dart 客户端?