Bad state: Mock method was not called within `when()`. Was a real method called?

There is one more possibility. If this happens to your mock object, then probably it may be outdated. In this case, try regenerating your mock objects by using

flutter pub run build_runner build --delete-conflicting-outputs

This issue may happen when you implement a method you want to mock instead of letting Mockito do that.

This code below will return Bad state: Mock method was not called within when(). Was a real method called?:

class MockFirebaseAuth extends Mock implements FirebaseAuth {
  FirebaseUser _currentUser;

  MockFirebaseAuth(this._currentUser);

  // This method causes the issue.
  Future<FirebaseUser> currentUser() async {
    return _currentUser;
  }
}

final user = MockFirebaseUser();
final mockFirebaseAuth = MockFirebaseAuth(user);

// Will throw `Bad state: Mock method was not called within `when()`. Was a real method called?`
when(mockFirebaseAuth.currentUser())
    .thenAnswer((_) => Future.value(user));

What do you want instead is:

class MockFirebaseAuth extends Mock implements FirebaseAuth {}

final user = MockFirebaseUser();
final mockFirebaseAuth = MockFirebaseAuth();

// Will work as expected
when(mockFirebaseAuth.currentUser())
    .thenAnswer((_) => Future.value(user));

Also this issue happens when you try to call when() on a non-mock sublass:

class MyClass {
  String doSomething() {
    return 'test';
  }
}

final myClassInstance = MyClass();

// Will throw `Bad state: Mock method was not called within `when()`. Was a real method called?`
when(myClassInstance.doSomething())
    .thenReturn((_) => 'mockedValue');