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:
I had the same problem. Using this answer I found the solution.
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.
Call setupFirebaseAuthMocks();
at the top of your main
function for all your tests.
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
});
}