我有一个测试,看看我的函数是否捕获了 FirebaseException,但事实并非如此。它将捕获 FirebaseFunctionsException。但是,它没有捕获 FirebaseException。这是我的测试,
test(
'Should return a RemoteDatabaseFailure when createEmployee is called and an exception is thrown on Firestore Set',
() async {
//arrange
when(mockFirebaseAuth.createUserWithEmailAndPassword(
email: anyNamed('email'), password: anyNamed('password')))
.thenAnswer((_) async => mockUserCredential);
when(mockUserCredential.user).thenReturn(mockUser);
when(mockUser.uid).thenReturn('uid');
when(mockFirebaseFunctions.httpsCallable(any))
.thenReturn(mockHttpsCallable);
when(mockHttpsCallable.call(any))
.thenAnswer((_) async => mockHttpsCallableResult);
when(mockFirebaseFirestore.collection(any))
.thenReturn(mockCollectionReference);
when(mockCollectionReference.doc(any)).thenReturn(mockDocumentReference);
when(mockDocumentReference.set(any))
.thenAnswer((_) async => throw FirebaseException(
code: 'code',
message: 'message',
plugin: 'plugin',
stackTrace: StackTrace.fromString('stackTrace'),
));
//act
final results = await employeeServiceFirebase.createEmployee(
email: employee.email,
employee: employee,
password: 'password',
roles: employee.roles,
);
//assert
expect(
results,
Right<Employee, Failure>(RemoteDatabaseFailure(
FailureCodes.REMOTE_DATABASE_EMP_ADD,
'message',
)));
});
这是我的功能:
try {
final credential = await _firebaseAuth.createUserWithEmailAndPassword(
email: employee.email,
password: password,
);
final createdEmployee = Employee.fromUser(credential.user, employee);
await _functions
.httpsCallable(FunctionsNames.ADDROLES)
.call(<String, dynamic>{'email': credential.user.email});
await _firebaseFirestore
.collection(CollectionNames.EMPLOYEES)
.doc(createdEmployee.id)
.set(createdEmployee.toMap(createdEmployee), SetOptions(merge: true));
return Left(employee);
} on FirebaseFunctionsException catch (error) {
await _crashlytics.recordError(
error,
StackTrace.empty,
reason: error.message,
printDetails: true,
);
return Right(FunctionsFailure(
FailureCodes.REMOTE_DATABASE_EMP_ADD,
error.message,
));
} on FirebaseException catch (error) {
await _crashlytics.recordError(
error,
error.stackTrace,
reason: error.message,
printDetails: true,
);
return Right(RemoteDatabaseFailure(
FailureCodes.REMOTE_DATABASE_EMP_ADD,
error.message,
));
还有,结果如下:
Expected: Right<Employee, Failure>:<Right(RemoteDatabaseFailure)>
Actual: Left<Employee, Failure>:<Left(Employee: {
id: hkHEd5OYnVPjYR4CHW6nf3nVKHB3,
email: email,
firstName: John,
lastName: Employee,
phoneNumber: 3045551111,
roles: [sales],
disabled: false,
})>
如您所见,它没有捕获(或不抛出)异常。这是一个错误还是我遗漏了什么?