4

I'm trying to test my firebase auth methods. Auth methods are signin, signout , register, etc. this are methods i want to perform unit test.

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

I tried to initialize Firebase.initializeApp in test main method its also doesn't work.

 class MockUserRepository extends Mock implements AuthService {
  final MockFirebaseAuth auth;
  MockUserRepository({this.auth});
 }
 class MockFirebaseAuth extends Mock implements FirebaseAuth{}
 class MockFirebaseUser extends Mock implements FirebaseUser{}
 class MockFirebase extends Mock implements Firebase{}
 void main() {
   MockFirebase firebase=MockFirebase();
   MockFirebaseAuth _auth = MockFirebaseAuth();
   BehaviorSubject<MockFirebaseUser> _user = BehaviorSubject<MockFirebaseUser>();
   when(_auth.onAuthStateChanged).thenAnswer((_){
      return _user;
     });
   AuthService _repo = AuthService.instance(auth: _auth);
   group('user repository test', (){
       when(_auth.signInWithEmailAndPassword(email: "email",password: "password")).thenAnswer((_)async{
  _user.add(MockFirebaseUser());
});
when(_auth.signInWithEmailAndPassword(email: "mail",password: "pass")).thenThrow((){
  return null;
});
test("sign in with email and password", () async {
  var signedIn = await _repo.onLogin(email:"testuser@test.com",password: "123456");
  expect(signedIn, isNotNull);
  expect(_repo.status, Status.Authenticated);
});

test("sing in fails with incorrect email and password",() async {
  var signedIn = await _repo.onLogin(email:"testuser@test.com",password: "666666");
  expect(signedIn, false);
  expect(_repo.status, Status.Unauthenticated);
});

test('sign out', ()async{
  await _repo.signout();
  expect(_repo.status, Status.Unauthenticated);
 });
});
} 

AuthService class

    enum Status { Uninitialized, Authenticated, Authenticating, 
    Unauthenticated }

   class AuthService with ChangeNotifier {
     FirebaseAuth auth = FirebaseAuth.instance;
     FirebaseUser _user;

    FirebaseUser get user => _user;

    set user(FirebaseUser value) {
      _user = value;
    }

    Status _status = Status.Uninitialized;

    Future<User> getCurrentUser() async {
      User currentUser;
      await FirebaseAuth.instance.authStateChanges().listen((User user) {
      currentUser = user;
      });
      return currentUser;
     }
    AuthService();
    AuthService.instance({this.auth}) {
       //    auth.onAuthStateChanged.listen((user) {
      //      onAuthStateChanged(user);
      //    });
      }

     Future<void> signout() async {
     await auth.signOut();
       }

     Future<User> createAccount({String email, String password}) async {
        try {
           UserCredential userCredential = await 
                  auth.createUserWithEmailAndPassword(
             email: email, password: password);
            return userCredential != null ? userCredential.user : null;
          } on FirebaseAuthException catch (e) {
           showToast(e.message);
          } catch (e) {
          log(e.toString());
           return null;
          }
       }

     Future<User> onLogin({String email, String password}) async {
      try {
        User user;
           await auth
        .signInWithEmailAndPassword(email: email, password: password)
      .then((value) {
        showToast("Login sucessful");
       user = value != null ? value.user : null;
      });
      return user;
     } on FirebaseAuthException catch (e) {
      showToast(e.message);
     }
    }

    sendResetPassword({String email}) async {
      bool isSent = false;
      try {
         await auth.sendPasswordResetEmail(email: email).then((value) {
           showToast("Reset password email sent");
            isSent = true;
        });
        return isSent;
       } on FirebaseAuthException catch (e) {
           showToast(e.message);
    }
  }

    Future<void> onAuthStateChanged(FirebaseUser user) async {
     if (user == null) {
       _status = Status.Unauthenticated;
        } else {
        _user = user;
        _status = Status.Authenticated;
       }
       notifyListeners();
     }

     Status get status => _status;

     set status(Status value) {
        _status = value;
        }
   }
Rahul sharma
  • 1,492
  • 12
  • 26

2 Answers2

7

Have a look at how they tested directly in firebase_auth code : https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_auth/firebase_auth/test

Call the setupFirebaseAuthMocks (you can adapt the code from here) method at the beginning of your main method and call await Firebase.initializeApp(); in a setUpAll method.

Eko
  • 1,487
  • 1
  • 18
  • 36
  • Great stuff, thanks. Just for clarification, you can pick the `mock_auth.dart` file over there and bring it to your test suite and use it. – dgilperez Nov 17 '20 at 20:16
  • Great answer, ty. Is there any way we can import this file from dependencies? I can't find it in the packages from pub.dev. – masus04 Apr 21 '22 at 14:16
-2

Firebase.initializeApp() is the solution for this. I am pretty sure. Try calling it in the file your are doing all these functions in their initState().

Szepetry
  • 52
  • 4