【问题标题】:PlatformException (PlatformException(channel-error, Unable to establish connection on channel., null, null)) while mocking method that use firestorePlatformException(PlatformException(通道错误,无法在通道上建立连接。,null,null))同时模拟使用firestore的方法
【发布时间】:2022-08-13 09:42:32
【问题描述】:

当我尝试对使用 Firestore 的方法进行单元测试时,我目前遇到了问题。 这是我要模拟的方法

Future<MediasState> loadMedias(AbstractEvent event) async {
    late AbstractBlocState streamState;
    try {
      DataHelper _dataHelperMediasEvent = DataHelperFactory.instance
          .createInstanceFromAnotherDataHelperAndEntityInstance(
              _dataHelperEvents, event, \'medias\');
      List<AbstractMedia> medias =
          (await _dataHelperMediasEvent.getAll()).cast<AbstractMedia>();
      for (AbstractMedia media in medias) {
        media.user = await (_dataHelperUsers.getEntity(media.user.get()));
      }
      medias = sortEntitiesByCreatedDateDesc(medias) as List<AbstractMedia>;
      streamState = MediasShowed(medias);
    } catch (error) {
      streamState = MediasShowedError();
    } finally {
      return streamState as MediasState;
    }
  }

这是我写的测试函数

 test(\'Test load medias\', () async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
    AbstractEvent event =
        EntityFactory.createInstance(\'Event\') as AbstractEvent;

    AbstractMedia media1 =
        EntityFactory.createInstance(\'Media\') as AbstractMedia;

    AbstractMedia media2 =
        EntityFactory.createInstance(\'Media\') as AbstractMedia;

    AbstractMedia media3 =
        EntityFactory.createInstance(\'Media\') as AbstractMedia;

    List<AbstractMedia> listOfMedias = <AbstractMedia>[];

    listOfMedias.add(media1);
    listOfMedias.add(media2);
    listOfMedias.add(media3);

    when(mockMediasEvent.loadMedias(event))
        .thenAnswer((_) async => MediasShowed(listOfMedias));

    blocMedias.add(LoadMediaOfOneEvent(event));

    await expectLater(blocMedias.state, isA<MediasShowedError>());
  });

不幸的是,当我运行此测试时出现此错误:\“PlatformException(通道错误,无法在通道上建立连接。,null,null) 包:firebase_core_platform_interface/src/pigeon/messages.pigeon.dart 199:7 FirebaseCoreHostApi.initializeCore\"

DataHelperFactory 创建一个需要 Firestore 实例的 DataHelper 实例。

class DataHelper {
  DataHelper.initialize(String collectionPath) {
    this.setCollection(collectionPath);
  }

  late String collectionPath;
  late String className;
  late CollectionReference<Map<String, dynamic>> collection;

  final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;

我已经尝试升级我的 firebase 依赖项,但问题仍然存在。我还在 Windows 和 Mac 设备以及朋友设备上进行了尝试,并且能够重现该问题。 欢迎任何关于如何修复我的测试的想法。

谢谢。

    标签: flutter firebase unit-testing mockito


    【解决方案1】:

    Flutter firebase testing 的文档指出需要使用模拟 firebase 库。他们更容易使用。

    【讨论】:

      猜你喜欢
      • 2022-07-12
      • 2022-07-23
      • 2022-07-07
      • 2021-11-25
      • 2019-10-04
      • 2022-08-12
      • 2022-11-02
      • 2021-01-02
      • 2022-10-24
      相关资源
      最近更新 更多