Flutter:通过存储库对 Firebase Firestore 进行单元测试

Flutter: Unit testing Firebase Firestore through Repository

我的目的是测试我的 Firestore 存储库方法。我发现了一个有用的 fake_cloud_firestore 包,它有助于模拟 firestore。

我有一个要测试的存储库方法:

@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());
    }
  }

还有一个测试:

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));
      });
    });

我想做的是在调用 Firestore 和更新文档时抛出一个异常,但是没有触发 when() 部分。当 运行 测试时我得到:

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

FakeFirebaseFirestore 和 UserRepository 构建:

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

看起来我的 firestore 调用在测试和存储库方法中看起来是一样的。我在这个 when() 部分中缺少什么?

出现错误是因为您使用的对象未扩展 Mock class from the mockito package where the when 函数来自。

您可以在单独的实用程序 class 中编写 Firestore 逻辑并模拟 class 并对其进行测试。