0

我在我的 Flutter 项目中使用 Firebase Phone Auth 并想测试我的 auth 类。我知道如何使用Mockito 和典型when()的s。.thenAnswer()Future

我想测试我的身份验证方法,特别是verificationFailed回调verificationCompleted

Future<void> getSmsCodeWithFirebase() async {
    try {
      await _firebaseAuth.verifyPhoneNumber(
        phoneNumber: fullPhoneNumber,
        timeout: const Duration(seconds: 30), 
        verificationCompleted: (credential) async {
          _firebaseSignIn(credential);
        },
        verificationFailed: (e) {
              errorMessage = 'Error code: ${e.code}';
          }
          initModelState = DataState.error;
        },
        codeSent: (String verificationId, int resendToken) {
          _firebaseSessionId = verificationId;
          initModelState = DataState.idle;
        },
        codeAutoRetrievalTimeout: (String verificationId) {},
      );
    } catch (ex) {
      errorMessage = 'There was some error';
      updateModelState = DataState.error;
    }
  }

现在我想出了这样的东西,但我不明白如何调用传递的回调。

    test('cant verify phonenumber', () async {
      when(mockFirebaseAuth.verifyPhoneNumber(
              phoneNumber: any,
              codeSent: anyNamed('codeSent'),
              verificationCompleted: anyNamed('verificationCompleted'),
              verificationFailed: anyNamed('verificationFailed'),
              codeAutoRetrievalTimeout: anyNamed('codeAutoRetrievalTimeout')))
          .thenAnswer((Invocation invocation) {
        // I need to put something here?
      });
      await authCodeViewModel.getSmsCodeWithFirebase();
      expect(authCodeViewModel.initModelState, DataState.error);
    });
4

1 回答 1

0

您并不是真的在问如何自己存根回调;您在询问如何为存根方法调用回调。您将使用与任何其他捕获的参数相同的捕获回调参数:

// Sample class with a method that takes a callback.
abstract class Foo {
  void f(String Function(int x) callback, int y);
}

@GenerateMocks([Foo])
void main() {
  var mockFoo = MockFoo();
  mockFoo.f((x) => '$x', 42);
  var captured = verify(mockFoo.f(captureAny, any)).captured;
  var f = captured[0] as String Function(int);
  print(f(88)); // Prints: 88
}

在你的情况下,我认为它会是这样的:

    test('cant verify phonenumber', () async {
      await authCodeViewModel.getSmsCodeWithFirebase();
      var captured = verify(mockFirebaseAuth.verifyPhoneNumber(
              phoneNumber: any,
              codeSent: anyNamed('codeSent'),
              verificationCompleted: anyNamed('verificationCompleted'),
              verificationFailed: captureNamed('verificationFailed'),
              codeAutoRetrievalTimeout: anyNamed('codeAutoRetrievalTimeout')))
          .captured;
      var verificationFailed = captured[0] as PhoneVerificationFailed;
      verificationFailed(FirebaseAuthException());
      expect(authCodeViewModel.initModelState, DataState.error);
    });

当然,如果提供回调,则不需要一开始就捕获它们;您可以自己直接调用它们。

于 2021-04-28T21:54:39.040 回答