我使用 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/