Widget测试-“ www.example.com ”则getter通道不是为MethodChannelFirebase类型定义的,目前的最佳做法是什么?

cunj1qz1  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(394)

之前我使用以下代码来确保Firebase被初始化。..

typedef Callback = void Function(MethodCall call);

void setupFirebaseAuthMocks([Callback? customHandlers]) {
  TestWidgetsFlutterBinding.ensureInitialized();

  setupFirebaseCoreMocks();

  ///todo fix this
  MethodChannelFirebase.channel.setMockMethodCallHandler((call) async {
    if (call.method == 'Firebase#initializeCore') {
      return [
        {
          'name': defaultFirebaseAppName,
          'options': {
            'apiKey': '123',
            'appId': '123',
            'messagingSenderId': '123',
            'projectId': '123',
          },
          'pluginConstants': {},
        }
      ];
    }

    if (call.method == 'Firebase#initializeApp') {
      return {
        'name': call.arguments['appName'],
        'options': call.arguments['options'],
        'pluginConstants': {},
      };
    }

    if (customHandlers != null) {
      customHandlers(call);
    }

    return null;
  });
}

自从我更新到最新版本的firebase_core后,这就不再起作用了:

firebase_core: ^2.9.0
# firebase_core: ^1.3.0
cloud_firestore: ^4.5.0

静态分析器指出没有为类型MethodChannelFirebase定义getter通道。..我的测试不能运行没有:

setupFirebaseAuthMocks();

  setUpAll(() async {
    await Firebase.initializeApp();
  });

我还尝试了(这是主应用程序中对firebase_core的新要求):

//setupFirebaseAuthMocks();

  setUpAll(() async {
    await Firebase.initializeApp(
      options: DefaultFirebaseOptions.currentPlatform,
    );
  });

在这里或文档中似乎没有一个明显的答案。如果你能给我指明方向我会非常感激的

wh6knrhe

wh6knrhe1#

发布我自己的答案以防其他人受益!
底线是你不再需要初始化应用程序来进行测试
Firebase.initializeApp(); //not required
相反,您必须确保在测试期间在应用程序中调用firebase时,它提供了一个合适的mock。如果提供了合适的mock,则可以避免错误消息:
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
如何提供模拟的示例如下所示

import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';

    final FakeFirebaseFirestore fakeFirebaseFirestoreManufacturersCollection = FakeFirebaseFirestore();

    initialiseFirestoreManufacturersCollectionFake() async {
  List<Manufacturer> testManufacturerList = [];

  testManufacturerList.add(Manufacturer(
      keyword: "none",
      id: "testManf1",
      countryOfOrigin: "United Kingdom",
      manufacturingLocations: [],
      distribution: [],
  ));

  testManufacturerList.forEach((manufacturer) async {
    await fakeFirebaseFirestoreManufacturersCollection
        .collection(FirestoreManufacturerUtils.manufacturersCollection)
        .doc(manufacturer.id)
        .set(manufacturer.toJson());
  });
}

main(){

  TestWidgetsFlutterBinding.ensureInitialized();
  
  

  setUpAll(() async {
    //await Firebase.initializeApp(); //no need for this anymore!
  });

  Widget testAppMultiTab({Widget? child}){

    ///before anything initialise the Firestore singleton with a Fake
    initialiseFirestoreManufacturersCollectionFake();
    var fakeFirebaseFirestoreManufacturersCollection = FirestoreFakerUtil.fakeFirebaseFirestoreManufacturersCollection;
    manufacturerInfo = ManufacturerInformation(firestore: fakeFirebaseFirestoreManufacturersCollection);
    
    return MaterialApp(
      home: Scaffold(
          body: ScopedModel<ManufacturerInformation>(model: manufacturerInfo,child: MaterialApp(
                        title: 'Manufacturing app',
                        home: HomeScreen(),
                      ),
                    ),
                  ),
                ),
              ))
      ),
    );
  }

  group("some tests which involve firestore calls", (){
  //...
  })
}


希望这能帮助到外面的人!!

0mkxixxg

0mkxixxg2#

是的,在firebase核心平台接口API中有一些突破性的变化。
您需要添加以下内容。会成功的

import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void setupFirebaseAuthMocks([Callback? customHandlers]) {
  TestWidgetsFlutterBinding.ensureInitialized();

  setupFirebaseCoreMocks();
}

您可以删除以下方法,因为channel已从最新依赖项中删除。

MethodChannelFirebase.channel.setMockMethodCallHandler((call) async { 

});

相关问题