Flutter: Unit testing Firebase Firestore through Repository

298

The error is coming up because you're using an object that does not extend the Mock class from the mockito package where the when function comes from.

You can write the Firestore logic in a separate util class and mock that class and test against that.

Share:
298
Donatas
Author by

Donatas

Updated on December 31, 2022

Comments

  • Donatas
    Donatas over 1 year

    I have a purpose to test my Firestore repository methods. I found out a useful fake_cloud_firestore package, which helps to mock firestore.

    I have a repository method that I want to test:

    @override
      Future<Either<UserFailure, UserDTO>> updateUser(FUser user) async {
        try {
          final UserDTO userDTO = UserDTO.fromDomainForUpdatingProfile(user);
    
          final Map<String, dynamic> userJson = userDTO.toJson();
    
          await _firestore
              .collection(FirestoreCollections.COLLECTION_USERS)
              .doc(user.id)
              .set(userJson, SetOptions(merge: true));
    
          return right(userDTO);
        } on FirebaseException catch (e) {
          if (e.message!.contains('PERMISSION_DENIED')) {
            return left(const UserFailure.insufficientPermission());
          } else {
            return left(const UserFailure.unexpected());
          }
        } on Exception {
          return left(const UserFailure.unexpected());
        }
      }
    

    And a test:

    test('exception test', () async {
            final Map<String, dynamic> jsonMap = json.decode(
              fixture("user/full_domain_fuser.json"),
            );
    
            final FUser fuser = FUser.fromJson(jsonMap);
            final userJson = UserDTO.fromDomainForUpdatingProfile(fuser).toJson();
    
            when(fakeFirebaseFirestore
                    .collection(FirestoreCollections.COLLECTION_USERS)
                    .doc(fuser.id)
                    .set(userJson, SetOptions(merge: true)))
                .thenThrow(Exception());
    
            final result = await userRepository.updateUser(fuser);
    
            expect(result, const Left(UserFailure));
          });
        });
    

    What I want to do is throw an Exception when calling Firestore and updating the document, but when() part is not being triggered. When running a test I get:

    Bad state: No method stub was called from within `when()`. Was a real method called, or perhaps an extension method?
    

    FakeFirebaseFirestore and UserRepository construction:

    FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();
    UserRepository userRepository = UserRepository(fakeFirebaseFirestore);
    

    It looks like that my firestore call looks the same in a test and also in repository method. What am I missing in this when() part?