在Flutter上模拟getExternalStorageDirectory

q5lcpyga  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(114)

我尝试模拟函数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;
  }
ekqde3dh

ekqde3dh1#

pub.dev所述:
path_provider现在使用PlatformInterface,这意味着并非所有平台都共享基于PlatformChannel的单一实现。有了这个变化,测试应该更新为模拟PathProviderPlatform而不是PlatformChannel
这意味着在test目录的某个地方创建以下mock类:

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您可以查看完整的示例。

相关问题