Scott Godfrey
Scott Godfrey

Reputation: 671

Bad state: No method stub was called from within `when()`

I am trying to test my catch in my signInAnonyymous() function. Yet, I am constantly getting the error stated in the title.

Here is my Mocked Auth class (edited for brevity):

class MockFirebaseAuth extends Mock implements FirebaseAuth {
  final bool signedIn;
  final bool isEmployee;

  MockFirebaseAuth({this.isEmployee = false, this.signedIn = false});

  @override
  Future<UserCredential> signInAnonymously() async {
  return MockUserCredential(isAnonymous: true);
  }
}

And, this is my test:

group('Sign-In-Anonymously', () {
setUp(() {
  mockFunctions = MockFirebaseFunctions();
  mockAuth = MockFirebaseAuth();
  mockCrashltyics = MockCrashlytics();
  mockFirestore = MockFirebaseFirestore();
  authRemoteService = AuthServiceFirebase(
    crashlytics: mockCrashltyics,
    firestoreService: mockFirestore,
    functions: mockFunctions,
    service: mockAuth,
  );
  authProvider = AuthProvider(authRemoteService);
});

test(
    'Should return a null AuthUser and non-null errorMessage on exception thrown',
    () async {
  when(mockAuth.signInAnonymously())
      .thenThrow(MockFirebaseAuthException('message', 'code'));
  //act
  await authProvider.signInAnonymously();
  //assert
  expect(authProvider.authUser, isNull);
  expect(authProvider.errorMessage, isNotNull);
});
});

I have researched and tried so many different ways and still can't test my catch. Any help would be appreciated. Thank you in advance.

Upvotes: 2

Views: 5200

Answers (1)

morrisseyd
morrisseyd

Reputation: 196

If you're going to use 'when', you can't override the method in the mock. You need to provide an answer from the "thenAnswer".

Upvotes: 6

Related Questions