firebase - 如何使用 Firebase 测试 Flutter 应用程序?

标签 firebase flutter unit-testing testing google-cloud-firestore

我使用 Flutter 和 Firebase 作为我的数据库。我想对我的应用程序进行一些单元测试,但是当我开始这个测试时:

testWidgets('MyWidget has a title and message', (WidgetTester tester) async {
    // Create the widget by telling the tester to build it.
    await tester.pumpWidget(LoginPage());

    expect(true, true);
});
我有异常(exception):

No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()


但是 Firebase.initializeApp() 在我的 main.dart 中被调用:
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
而且我不知道如何在我的测试中初始化 Firebase 应用程序。

最佳答案

将此作为社区维基发布,因为它基于@GuilhermeGabanelli 的评论。
如果您检查 this flutterfire documentation关于如何使用 Firebase 服务执行单元测试,您将看到:

The Firebase libraries need to run on an actual device or emulator. So if you want to run unit tests, you'll have to use Fakes instead. A Fake is a library that implements the API of a given Firebase library and simulates its behavior.

...

When initializing your app, instead of passing the actual instance of a Firebase library (e.g. FirebaseFirestore.instance if using Firestore), you pass an instance of a fake (e.g. FakeFirebaseFirestore()). Then the rest of your application will run as if it were talking to Firebase.


接下来是带有示例代码的示例。我相信这是您面临的问题的原因,如果您更改代码以使用 Fakes,则应该解决此问题。

关于firebase - 如何使用 Firebase 测试 Flutter 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68164035/

相关文章:

javascript - firebase 函数在 onCreate firestore 事件中删除了错误流

javascript - 创建带有“belongsTo”关系错误的记录 - Ember.js

flutter - 如何从 FutureBuilder 返回不同的 MaterialApp 小部件

flutter - 按下添加按钮后如何使我的文字输入消失?

javascript - Firebase 不会保存具有空值的键

Firebase 远程配置 : Uncaught TypeError: firebase. remoteConfig 不是函数

android - 如何在 Flutter 中调整图标/图标按钮的大小?

unit-testing - 仅根据spock的调用次数模拟出方法的返回

unit-testing - 单元测试术语概述( stub 与模拟、集成与交互)?

c# - 在 C# 项目中包含用于单元测试的资源文件