How to mock the FirebaseApp in flutter

后端 未结 3 699
难免孤独
难免孤独 2021-01-22 09:32

I am trying to test a method that uses FirebaseFirestore but I am not able to mock the FirebaseFirestore.instance property.

I am following these examples:

  1. In
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 09:45

    I had the same problem. Using this answer I found the solution.

    1. Copy the contents of: https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_auth/firebase_auth/test/mock.dart into a file, that you can import into your tests, where you need to initialize a Firebase app.

    2. Call setupFirebaseAuthMocks(); at the top of your main function for all your tests.

    3. In your setUpAll function, call await Firebase.initializeApp(); (You can also put this in your main function under setupFirebaseAuthMocks(); will still work).

    Now you should have a mocked Firebase app.

    Here is a full example:

    import 'package:flutter/material.dart';
    import 'package:firebase_core/firebase_core.dart';
    import 'package:flutter_test/flutter_test.dart';
    import '../lib/authentication/your_auth_using_firebase.dart';
    import './mock.dart'; // from: https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_auth/firebase_auth/test/mock.dart
    
    
    
    void main() {
      // TestWidgetsFlutterBinding.ensureInitialized(); Gets called in setupFirebaseAuthMocks()
      setupFirebaseAuthMocks();
    
      setUpAll(() async {
        await Firebase.initializeApp();
      });
    
      testWidgets('Your Test', (WidgetTester tester) async {
        final YourFirebaseAuthClass authService = YourFirebaseAuthClass();
        // Tests to write
      });
    }
    

提交回复
热议问题